apply(mtcars[,c('vs','am')],2,table)
produces
vs am
0 18 19
1 14 13
but
lapply(mtcars[,c('vs','am')],table)
produces
$vs
0 1
18 14
$am
0 1
19 13
Can I force lapply to do produce one table as apply does?
In the end I would like to compute means using different dependent variables with identical values. I use lapply but do not want to have to perform a cbind in the end:
func.break <- function(indy){
t(as.data.frame(mtcars
%>% group_by(get(indy))
%>% summarise_at(depy, funs(mean))
)
)
}
indy <- c('vs','am')
depy <- c('mpg','qsec')
res.list <- lapply(indy,func.break)
res.list
[[1]]
[,1] [,2]
get(indy) 0.00000 1.00000
mpg 16.61667 24.55714
qsec 16.69389 19.33357
[[2]]
[,1] [,2]
get(indy) 0.00000 1.00000
mpg 17.14737 24.39231
qsec 18.18316 17.36000
cbind(as.data.frame(res.list[1]),as.data.frame(res.list[1]))
X1 X2 X1 X2
get(indy) 0.00000 1.00000 0.00000 1.00000
mpg 16.61667 24.55714 16.61667 24.55714
qsec 16.69389 19.33357 16.69389 19.33357
I guess there is a more elegant way? How would apply work for this?
Try list2DF
list2DF(lapply(mtcars[, c("vs", "am")], table))
which gives
vs am
1 18 19
2 14 13
Update
Or you can try as.data.frame
> as.data.frame(lapply(indy, func.break))
X1 X2 X1.1 X2.1
get(indy) 0.00000 1.00000 0.00000 1.00000
mpg 16.61667 24.55714 17.14737 24.39231
qsec 16.69389 19.33357 18.18316 17.36000