Write a dataframe with different number of decimal places per column in R

ぐ巨炮叔叔 提交于 2019-12-23 10:06:47

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/17093416/write-a-dataframe-with-different-number-of-decimal-places-per-column-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!