I’m attempting to generate new variables in a data frame that are conditional on two (or more) other variables in the data frame. I believe that the looping functions in R (i.e., lapply, sapply, etc.) are useful and efficient for this purpose. Something is not right, however, with my approach, and I can’t figure out what.
M <- data.frame(x=c("A", "A", "B", "B"), y=c(1,2,1,2))
Using this data frame, I would like to generate a new column z, containing logicals that are TRUE iff both x == "A" and y == 1. The following code is the best I can come up with here, but only seems to evaluate my first condition.
M$z <- sapply(M$x, function(x,y) if((x == "A") && (y == 1)) T else F, M$y)
- Can this code be fixed for my purpose?
- Is there a better way of doing this in R, perhaps using other looping functions?
This is a task for
transformfunctionI think an even simpler approach would be