1

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 
Adam Waring
  • 1,158
  • 8
  • 20
CrunchyTopping
  • 803
  • 7
  • 17
  • The error is from c(i, "diet", "chick"). What are you trying to do here? You are trying to index by values in the column ChickWeight$weight and "diet" and "chick" which obviously doesn't make sense. – Adam Waring Feb 19 '19 at 12:54

1 Answers1

1

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.

CrunchyTopping
  • 803
  • 7
  • 17
Adam Waring
  • 1,158
  • 8
  • 20