How to apply a custom function to every value in a dataframe?

Viewed 26

I am trying to apply a custom function to every value of a dataframe. Here is the custom function and dataframe:

#function
test_fun <- function(x, y = 1) {

output <- x + y
output
}

#dataframe
df <- data.frame(a = c(1,2,3), b = c(4,5,6))

Now lets say I want to apply test_fun, with y = 2, to every value of df. This method doesn't seem to work:


lapply(df, test_fun(y = 2))

1 Answers

The function is vectorized, we can directly apply over the dataset

test_fun(df, y = 2)
#  a b
#1 3 6
#2 4 7
##3 5 8

Regarding the OP's error, if we are not using lambda function, specify the argument as

lapply(df, test_fun, y = 2)

-output

#$a
#[1] 3 4 5

#$b
#[1] 6 7 8

Or specify the lambda function and then use (y = 2)

lapply(df, function(vec) test_fun(vec, y = 2))
Related