在write.csv中控制R中的数字 [英] Controlling digits in R in write.csv

查看:156
本文介绍了在write.csv中控制R中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据框写入csv,其中包含数字列和字符列。

I want to write a data frame into csv which contains numeric columns as well as character columns.

一些数字列是整数,我想显示为整数,有些是小数,我需要控制小数后的位数,显然没有变化的字符列

Some numeric columns are integers which I want to display as integers and some are decimals in which I need to control the number of digits after decimal and obviously no change in character columns

我如何做到这一点?
该数据框中的特定行是

How can I do this? Eq a particular row in that dataframe is

XYZ  8200  0.306060606 ABC

输出应为

XYZ 8200 0.30 ABC

回答

推荐答案

这将强制小数位后面两位数字:

This will force two digits after the decimal place:

# read in some sample data
xyz <- data.frame(v1 = c("a", "b"), 
                  v2 = c(8200, 8100), 
                  v3 = c(365.2121, 365.2122), 
                  v4 = c(0.3060, 0.3260))

format(xyz, digits=2, nsmall=2)
#  v1      v2     v3   v4
#1  a 8200.00 365.21 0.31
#2  b 8100.00 365.21 0.33

如果不希望具有整数的列也有这些小数位(例如,在这个例子中,列 v2 ),你可以做一些事情,例如将 xyz 格式化和其他列:

If you don't want columns with whole numbers to also have those decimal places (e.g. column v2 in this example), you could do something like splitting xyz into columns that need to be formatted and other columns:

numbs2format <- 
    xyz[, (sapply(xyz, function(x) isTRUE(sum(x %% 1) > 0)))]
# ignore the warnings from trying to use %% on non-numerics
other.columns <- 
    xyz[, (sapply(xyz, function(x) !isTRUE(sum(x %% 1) > 0)))]

cbind(other.columns, format(numbs2format, digits=2, nsmall=2))
#  v1   v2     v3   v4
#1  a 8200 365.21 0.31
#2  b 8100 365.21 0.33

这篇关于在write.csv中控制R中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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