CrunchyTopping
CrunchyTopping

Reputation: 814

Undefined columns error when using lapply

Why does this work and not the lapply?

Using the built in base R ChickWeight data:

names(ChickWeight)<-tolower(names(ChickWeight)) 

This works if I just want one correlations for 1 column, "time":

library(reshape)
cor(cast(melt(ChickWeight[,c("time","diet","chick")],id.vars=c("chick","diet")),chick~diet))

This doesn't when I try to apply the same thing to both "time" and "weight", i.e. columns 1:2:

lapply(as.list(ChickWeight[,c(1:2)]), FUN=function(i){
cor(cast(melt(ChickWeight[,c(i,"diet","chick")], id.vars=c("chick","diet")),chick~diet))
})

So the fact that the function part works fine by itself makes me think there's something I don't understand about using lapply like this. I get this error:

Error in `[.data.frame`(ChickWeight, , c(i, "diet", "chick")) : 
  undefined columns selected 

Upvotes: 1

Views: 144

Answers (1)

Adam Waring
Adam Waring

Reputation: 1268

Ah I see what you are trying to do here now.

Replace:

lapply(as.list(ChickWeight[,c(1:2)]), .........

With

lapply(names(ChickWeight)[1:2], .............

You are passing the column values when what you want is the column name.

Upvotes: 1

Related Questions