【问题标题】:R: Create a table where cells have 1 or 0 decimal places after rbindR:创建一个表格,其中单元格在 rbind 后有 1 或 0 位小数
【发布时间】:2019-11-08 14:55:10
【问题描述】:

我正在 R 中创建一个表格。某些行中的值应该有 0 个小数位(例如人数),而其他行中的值应该有 1 个小数位(例如人口百分比)。

我有数据框,然后使用R中的round函数round函数创建两个表-round0(小数点后0位)和round1(小数点后1位)。

round1<-round(prof.table[-c(2:3),], 1)
round0<-round(prof.table[2:3,], 0)

prof.table<-rbind(round0, round1)

将它们组合后,我希望round0 表中的值小数点后为零,而round1 中的值小数点后1 位。但是,在 rbind 之后,所有单元格中的值都有 1 个小数位,所以我的整数显示为 nnn.0。如何从整数中删除这个多余的小数位?

【问题讨论】:

  • 你所问的不能用数字来完成,只有当你强制数据到类"character"时。这是因为这些数字仍然有 16 位小数,它们被四舍五入但仍被编码为 C 语言类型"double",64 位实数。
  • 感谢您的解释!我需要在报告中显示数据,所以我在一轮之后使用as.character 命令让它显示没有小数点。 r round1&lt;-round(prof.table[-c(2:3),], 1) round1$`V1`&lt;-as.character(round1$`V1`) round1$`V2`&lt;-as.character(round1$`V2`) round0&lt;-round(prof.table[2:3,], 0) round0$`V1`&lt;-as.character(round0$`V1`) round0$`V2`&lt;-as.character(round0$`V2`) prof.table&lt;-rbind(round0, round1)

标签: r rbind kable


【解决方案1】:

您正在尝试将 numeric 值与 integer 组合。一个向量(或 data.frame 列)只能有一个类。它要么将数字强制为整数,要么将整数强制为数字。鉴于此选择,后者更可取,因为将2 转换为2.0000 不会丢失数据。

这将有助于解释类的差异:What's the difference between integer class and numeric class in R

一个例子:

# create an integer vector x (0 decimal places) & numeric vector y (>0 decimal places)
x <- as.integer(1:3)
y <- runif(3)

# check their classes to confirm
class(x)
class(y)

# bind them together, and view class
z <- c(x, y)
z
class(z)

【讨论】:

    【解决方案2】:

    由于我需要将数据显示在表格中,因此我按照@Rui 的建议将数据强制转换为字符格式,并感谢@Jonny 提示向量只能是一个类:

    
    #Round certain variables to one decimal point
    round1<-round(prof.table[-c(2:3),], 1) 
    
    #set as character
    round1$`V1`<-as.character(round1$`V1`) 
    round1$`V2`<-as.character(round1$`V2`) 
    
    #Round others to zero decimal point
    round0<-round(prof.table[2:3,], 0) 
    
    #set them as character
    round0$`V1`<-as.character(round0$`V1`) 
    round0$`V2`<-as.character(round0$`V2`) 
    
    #combine into data frame
    prof.table<-rbind(round0, round1) 
    
    

    【讨论】:

    • 还有一点,只有当列名以数字开头、有特殊字符、有空格等时才需要反引号。格式良好的名称,如V1V2 不需要他们。 (但有反引号并没有什么坏处。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2012-08-07
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多