Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

I have a function f(var1, var2) in R. Suppose we set var2 = 1 and now I want to apply the function f() to the list L. Basically I want to get a new list L* with the outputs

[f(L[1],1),f(L[2],1),...,f(L[n],1)]

How do I do this with either apply, mapply or lapply?

1 Answer

0 votes
by
edited by

To apply a function to multiple parameters, you can pass an extra variable while using any apply function.

Here are some examples:

vars1<-c(5,6,7)

vars2<-c(10,20,30)

myFun <-function(var1,var2)

{

  var1*var2

}

mapply(mult_one,vars1,vars2)

[1] 10 40 90

mylist <- list(a=10,b=20,c=30)

myfun <- function(var1,var2){

  var1*var2

}

var2 <- 5

sapply(mylist,myfun, var2=var)

  a   b   c 

 50 100 150

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...