using anonymous functions in R with multiple arguments
anonymous-function, dataframe, loops, r
Solution
This is a task for `transform` function
transform(M, z=ifelse((x == "A") & (y == 1), T, F))
x y z
1 A 1 TRUE
2 A 2 FALSE
3 B 1 FALSE
4 B 2 FALSE
I think an even simpler approach would be
M$z <- with(M, (x == "A") & (y == 1))
M
x y z
1 A 1 TRUE
2 A 2 FALSE
3 B 1 FALSE
4 B 2 FALSE
Problem
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?