应用分类变量

tapply with categorical variable

我正在尝试使用 tapply() 进行一些描述性分析,使用 R 中的 mtcars 数据集。

所以问题是:

> table(mtcars$carb)

 1  2  3  4  6  8 
 7 10  3 10  1  1 
> tapply(mtcars$carb,list(mtcars$vs,mtcars$am),function(x){length(x)})
   0 1
0 12 6
1  7 7

上面一行有效,但下面一行没有:

> tapply(mtcars$carb,list(mtcars$vs,mtcars$am),function(x){table(x)})
  0         1        
0 Integer,3 Integer,4
1 Integer,3 Integer,2

通过在 mtcars$carb 上使用 tapply,我希望从 vs 和 am 的四种组合中的每一种都得到 table。知道出了什么问题吗?非常感谢。

计算已由 tapply 完成,但无法以易于查看的形式提供。您可以将 table 的输出包装在 list.

tapply(mtcars$carb,list(mtcars$vs,mtcars$am),function(x) list(table(x)))

#[[1]]
#x
#2 3 4 
#4 3 5 

#[[2]]
#x
#1 2 4 
#3 2 2 

#[[3]]
#x
#2 4 6 8 
#1 3 1 1 

#[[4]]
#x
#1 2 
#4 3 

或使用lapply

temp <- tapply(mtcars$carb,list(mtcars$vs,mtcars$am),table)
lapply(temp, I)

我们可以用 fable

ftable(mtcars[c('carb', 'vs', 'am')])