mardi 20 janvier 2015

Using lapply to generate new variables across data sets, conditional on not existing

Let's say I have three data sets:



df1 <- data.frame(var1 = c(1,2,3), var2 = c(1,2,3))
df2 <- data.frame(var1 = c(1,2,3), var2 = c(1,2,3))
df3 <- data.frame(var1 = c(1,2,3), var2 = c(1,2,3), var3 = c(1,2,3))


I would like to check to see if a variable "var3" exists within each dataset. If it doesn't, I would like to generate an empty variable called "var3". Here is what I am trying:



dframes <- list(df1,df2,df3)

lapply(dframes, function(df) {
ifelse("var3" %in% colnames(df), print("var3 exists"), df$var3 <- NA)
})


The output comes out as:



[[1]]
[1] NA

[[2]]
[1] NA

[[3]]
[1] "var3 exists"


And the desired "var3" variable isn't generated for the first two data sets - they still only contain "var1" and "var2".


You're help is appreciated.


Aucun commentaire:

Enregistrer un commentaire