Apply function with multiple parameters in R




I created function f(x,y) in R. I want to set set y = 1 and then I want to apply the function f() to the list L so that I get a new list after applying the function to it.

The list members will be the first argument to the function.

how can I go about doing this in R?

# Simple add function
sum <-function (x = list(),y){x+y}
#The list you want to use
L <- list(1,2,3)
#Create an empty list to which all the data will be added
l_null <- list()
len <- length(L)
#Loop through all the items in the list and apply the function to each
for (i in 1:len){
        l_null[[i]] <- sum(L[[i]],1)

The L[[i]] part extracts the value from the list L where the index = i.

> str(l_null)
List of 3
 $ : num 2
 $ : num 3
 $ : num 4

Hope this helps!!


Is there any way to do it using sapply or something similar?


I am sorry but I am not aware of doing such operations using sapply.
May be @ajay_ohri sir @kunal sir will be able to help you out.!!


[1] 1 2 3 4 5 6 7 8 9 10
int [1:10] 1 2 3 4 5 6 7 8 9 10
[1] 3 5 7 9 11 13 15 17 19 21

so just pass the list as a parameter as @shuvayan said

but try lapply

lapply {base} R Documentation
Apply a Function over a List or Vector


lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.