I need to generate a dataframe or data.table which has different number of decimal places per column.
For example:
Scale Status
1.874521 1
Needs to be print in a CSV as:
Scale, Status
1.874521, 1.000
This has to be as a numeric value as I have tried format(DF$status, digits=3)
and as.numeric(format(DF$status, digits=3))
however this converts it to characters which when exported to CSV has double quotes ".
My actual dataframe has lots of columns with different amounts of decimal places required as well as characters which do need to be double quoted so I can't apply a system wide change.
A better option than doing quote=FALSE
, is to actually specify which columns you want quoted, as the quote
param can be a vector of column indices which you want to be quoted. E.g.
d = data.table(a = c("a", "b"), b = c(1.234, 1.345), c = c(1, 2.1))
d[, b := format(b, digits = 2)]
d[, c := format(c, nsmall = 3)]
d
# a b c
#1: a 1.2 1.000
#2: b 1.3 2.100
write.csv(d, 'file.csv', quote = c(1,2), row.names = F)
#file.csv:
#"a","b","c"
#"a","1.2",1.000
#"b","1.3",2.100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With