[R] more complex by with data.table???
Ramiro Barrantes
ramiro at precisionbioassay.com
Tue Jun 9 22:22:01 CEST 2015
Hello,
I am trying to do something that I am able to do with the "by" function within data.frame but can't figure out how to achieve with data.table.
Consider
dt<-data.table(name=c(rep("a",5),rep("b",6)),var1=0:10,var2=20:30,var3=40:50)
myFunction <- function(x) { mean(x) }
I am aware that I can do something like:
dt[, .(meanVar1=myFunction(var1)) ,by=.(name)]
but how could I do the equivalent of:
df<-data.frame(name=c(rep("a",5),rep("b",6)),var1=0:10,var2=20:30,var3=40:50)
myFunction <- function(x) { mean(x) }
columnNames <- c("var1","var2","var3")
result <- by(df, df$name, function(x) {
output <- c()
for(col in columnNames) {
output[col] <- myFunction(x[,col])
}
output
})
do.call(rbind,result)
Thanks in advance,
Ramiro
[[alternative HTML version deleted]]
More information about the R-help
mailing list