组合R表函数中的列

Moh*_*han 1 r dataframe

我目前正在学习R,我遇到了制表数据的问题.

我在数据框中有整数分数model,范围从1到10(含).当我使用表函数时,即

table(model$score)
Run Code Online (Sandbox Code Playgroud)

我得到以下结果:

  1  2  3  4  5  6  7  8  9 10
  5  6  8  7  2  3  6  4  5  0
Run Code Online (Sandbox Code Playgroud)

但是,我想按以下格式制表数据:

  1-2  3-4  5-6  7-8  9-10
   11   15    5   10     5
Run Code Online (Sandbox Code Playgroud)

是否可以通过表函数实现此功能,还是必须寻求其他功能/包的帮助?那我该怎么办?这个prop.table功能有类似的方法吗?

谢谢您的帮助.

李哲源*_*李哲源 6

为什么不简单地这样做?

x <- table(model$score)
x <- x[c(1,3,5,7,9)] + x[c(2,4,6,8,10)]
names(x) <- c("1-2","3-4","5-6","7-8","9-10")
Run Code Online (Sandbox Code Playgroud)

它根本不会带来额外的复杂性.

table 当然会给你一个长度为10的向量,因为你有10个独特的等级.

好吧,如果你坚持要求table()得到你想要的结果,你需要cut()用来将你的数据分类到箱子里:

set.seed(0); a <- sample(1:10, 200, replace = TRUE)
table(cut(a, breaks = c(0,2,4,6,8,10)))

 (0,2]  (2,4]  (4,6]  (6,8] (8,10] 
    29     45     43     47     36 
Run Code Online (Sandbox Code Playgroud)

改变标签?使用labels(内部cut()):

table(cut(a, breaks = c(0,2,4,6,8,10), labels = c("1-2","3-4","5-6","7-8","9-10")))

 1-2  3-4  5-6  7-8 9-10 
  29   45   43   47   36 
Run Code Online (Sandbox Code Playgroud)

但你必须确保a数字.如果出现以下情况,您将收

a <- factor(a)
table(cut(a, breaks = c(0,2,4,6,8,10)))

Error in cut.default(a, breaks = c(0, 2, 4, 6, 8, 10)) : 
  'x' must be numeric
Run Code Online (Sandbox Code Playgroud)