# Apply function with multiple parameters in R

#1

Hello,

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?

#2
``````# 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)
l_null
}
``````

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!!

#3

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

#4

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.!!

#5

funxy=function(x,y){2*x+y}
a=1:10
a
[1] 1 2 3 4 5 6 7 8 9 10
str(a)
int [1:10] 1 2 3 4 5 6 7 8 9 10
funxy(a,1)
[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

https://stat.ethz.ch/R-manual/R-devel/library/base/html/lapply.html

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

Description

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.