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)
Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.
An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.
What are anonymous functions in R? Anonymous functions are those functions which are not assigned a variable name. These functions are also known as lambda functions (just like the ones in python) These functions are just created for the time being and are used without defining a variable name to them.
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
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
Take a look at mapply:
> M$z <- mapply(M$x,M$y, FUN=function(x,y) if((x == "A") && (y == 1)) T else F)
> M
x y z
1 A 1 TRUE
2 A 2 FALSE
3 B 1 FALSE
4 B 2 FALSE
Apropos, this has nothing to do with anonymous functions and everything to do with applying with multiple arguments. If you named the function it would still not work in any of the single-argument apply variants.
The other way to do this would be to ddply
by row, or split your data.frame into a list with each row being a separate entry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With