Reputation: 23
I am trying to use the apply method in R. But I keep getting the error: Error in FUN(newX[, i], ...) : missing argument in "b".
The code which produces the error:
my_data <- data.frame(x1 = 1:5, x2 = 2:6, x3 = 3)
myFunction <- function(a, b, c){
return(a + b + c)
}
results = apply(my_data, 1, myFunction) #this line is producing the error massage
If I change "myFunction" to "sum" for example. Then there is no error. How can I get rid of this error?
Upvotes: 1
Views: 383
Reputation: 3412
Also note your data.frame is a list of 3 vectors. You can add vectors just like a scalar.
with(my_data, x1 + x2 + x3)
Upvotes: 1
Reputation: 887118
Either the function should be changed to
myFunction <- function(x) sum(x)
apply(my_data, 1, myFunction)
#[1] 6 8 10 12 14
Also, the sum operation by row is more efficient with rowSums
rowSums(my_data)
or specify the arguments separately by using a lambda/anonymous function in the OP's original function
apply(my_data, 1, function(x) myFunction(x[1], x[2], x[3]))
Upvotes: 2