1
votes

Given a data frame:

set.seed(1)
df <- data.frame(a=1:10,b=runif(10),c=10*runif(10),d=101:110)

each columns format I expect:

%2s , %3.1f, %4.3f, %4.1f

how to apply the fmt on relative columns?

Supplement: the data frame will be saved as txt file which is the input data of another software. So I need to keep each columns as numeric data except the first column.

Maybe I ignored the format of R. Further explaination: format %3.1f means this cell is 3 character width with 1 decimal digit. It is a numeric ,not character (string). %2s mean output 2 width length character, etc..

1
No, you can save characters to a text file and import as numbers into the other software. Just set quote = FALSE in write.table. - Roland

1 Answers

3
votes

You can use Map to iterate over two inputs. Then you can assign into the data.frame:

df[] <-  Map(sprintf, fmt, df)

or use this to create a separate data.frame:

"[<-"(df,,value = Map(sprintf, fmt, df))
#    a   b     c     d
#1   1 0.3 2.060 101.0
#2   2 0.4 1.766 102.0
#3   3 0.6 6.870 103.0
#4   4 0.9 3.841 104.0
#5   5 0.2 7.698 105.0
#6   6 0.9 4.977 106.0
#7   7 0.9 7.176 107.0
#8   8 0.7 9.919 108.0
#9   9 0.6 3.800 109.0
#10 10 0.1 7.774 110.0