Write a dataframe with different number of decimal places per column in R
我需要生成每列具有不同小数位数的数据框或 data.table。
例如:
|
1
2 |
Scale Status
1.874521 1 |
需要以 CSV 格式打印为:
|
1
2 |
Scale, Status
1.874521, 1.000 |
这必须是一个数值,因为我尝试过 format(DF$status, digits=3) 和 as.numeric(format(DF$status, digits=3)) 但是这会将其转换为在导出到 CSV 时具有双引号的字符”。
我的实际数据框有很多列,需要不同的小数位数以及需要双引号的字符,因此我无法应用系统范围的更改。
- write.csv 有一个 quote 选项,您可以将其设置为 FALSE。
- 你可以在 write.csv 中使用 quote = FALSE 吗?
- quote=FALSE 肯定会按照他的要求去做。我只是想知道在 data.frame 他是否还有字符列需要用双引号打印。
- @Michele 是对的,由于某些字符列,我无法设置 quote=FALSE
比执行 quote=FALSE 更好的选择是实际指定要引用的列,因为 quote 参数可以是要引用的列索引的向量。例如
|
1
2 3 4 5 6 7 8 9 10 11 12 13 |
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) |
- 非常感谢您。我现在有一个工作解决方案,使用 as.data.table(DF[,STATUS:= format(STATUS, nsmall=3)]) 并将向量添加到 quote 参数。非常简单和优雅的解决方案。谢谢。
来源:https://www.codenong.com/17093416/
