Skip to content
Prev 334745 / 398503 Next

2 factor split and lapply

Sure, here is a reproducible example:

testframe<-data.frame(factor1=c("a","b","a"),factor2=c(1,2,2),data=c(3.34,4.2,2.1))

splitframe<-split(testframe,list(factor1=testframe$factor1,factor2=testframe$factor2))

lapply(splitframe,function(x)mean(x[,"data"]))

The above lapply returns

$a.1
[1] 3.34

$b.1
[1] NaN

$a.2
[1] 2.1

$b.2
[1] 4.2

The results are correct but not presented in a format I prefer... Factor1 and factor2 are combined into a single factor, which is not desired. I want to keep them seperate. Ideally, a table output as below.

     a          b
1   3.34     NaN
2   2.1       4.2

How can I achieve this please?