I can use the tapply function to make basic operations (e.g. using mtcars data, calculate mean weight by number of cylinders).
library(data.table)
mtcars <- data.table(mtcars)
tapply(X = mtcars[,wt],
INDEX = mtcars[,cyl],
mean)
However, I do not know how to perform more complex operations. E.g. Correlation between weight and qsec variables by number of cylinders. I tried something like the following but it does not work.
tapply(X = mtcars[,.(wt, qsec)],
INDEX = mtcars[,cyl],
cor.test(mtcars[,wt], mtcars[,qsec]))
Error in match.fun(FUN) : 'cor.test(mtcars[, wt], mtcars[, qsec])' is not a function, character or symbol
tapply(X = rownames(mtcars[,.(wt,qsec,cyl)]),
INDEX = mtcars[,cyl],
function(r) cor.test(mtcars[r, 1],
mtcars[r, 2])
Any idea how to do this efficiently with an t/apply function?