1

I am trying to use tapply() for some descriptive analysis, with the mtcars dataset in R.

So the problem is:

> 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

The above line worked, but the line below didnt:

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

By using tapply on mtcars$carb, I expect to get the table for each of the four combinations from vs and am. Any idea what went wrong? Thank you very much.

user11806155
  • 121
  • 5

2 Answers2

0

The calculation is already done by tapply but it is not available in easy to view form. You can wrap the output of table in 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 

Or using lapply :

temp <- tapply(mtcars$carb,list(mtcars$vs,mtcars$am),table)
lapply(temp, I)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can do this with fable

ftable(mtcars[c('carb', 'vs', 'am')])
akrun
  • 874,273
  • 37
  • 540
  • 662