【问题标题】:tapply with categorical variable带有分类变量的 tapply
【发布时间】:2020-10-14 06:58:54
【问题描述】:

我正在尝试使用 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(mtcars$carb, mtcars$vs, mtcars$am)?

标签: r tapply


【解决方案1】:

计算已由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)

【讨论】:

    【解决方案2】:

    我们可以通过fable 做到这一点

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

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 2023-02-18
      • 2012-11-09
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 2020-07-22
      • 2018-11-16
      相关资源
      最近更新 更多