首页 > 解决方案 > R:创建一个表格,其中单元格在 rbind 后有 1 或 0 位小数

问题描述

我在 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。如何从整数中删除这个额外的小数位?

标签: rrbindkable

解决方案


您正在尝试将numericvalue 与integer. 一个向量(或 data.frame 列)只能有一个类。它要么将数字强制为整数,要么将整数强制为数字。鉴于这种选择,后者更可取,因为转换22.0000.

这将有助于解释类中的差异: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)

推荐阅读