在R中写入每列不同位数的数据框 [英] Write a dataframe with different number of decimal places per column in R

查看:374
本文介绍了在R中写入每列不同位数的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个数据帧或data.table,每列具有不同的小数位数。



例如:

 比例状态
1.874521 1

需要以CSV格式打印:

 规模,状态
1.874521,1.000

这必须是一个数值,因为我试过格式(DF $ status,digits = 3) as.numeric(format(DF $ status,digits = 3))然而,这将转换为字符,当导出为CSV时,双引号。



我的实际数据框有许多需要使用不同数量小数位的列,以及需要双引号的字符,所以我不能应用系统的变化。

解决方案

quote = FALSE 更好的选择是实际指定要引用哪些列,如引用 param可以是您要引用的列索引的向量,例如

  d =数据。(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
#abc
#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
/ pre>

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

这篇关于在R中写入每列不同位数的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆