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
?
Just pass var2 as an extra argument to one of the apply functions.
mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
var1*var2
}
var2 <- 2
sapply(mylist,myfxn,var2=var2)
This passes the same var2
to every call of myfxn
. If instead you want each call of myfxn
to get the 1st/2nd/3rd/etc. element of both mylist
and var2
, then you're in mapply
's domain.
If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply
as follows:
vars1 <- c(1, 2, 3)
vars2 <- c(10, 20, 30)
mult_one <- function(var1, var2)
{
var1*var2
}
mapply(mult_one, vars1, vars2)
which gives you:
> mapply(mult_one, vars1, vars2)
[1] 10 40 90
To further generalize @Alexander's example, outer
is relevant in cases where a function must compute itself on each pair of vector values:
vars1 <- c(1,2,3)
vars2 <- c(10,20,30)
mult_one <- function(var1, var2)
{
var1*var2
}
outer(vars1, vars2, mult_one)
gives:
> outer(vars1, vars2, mult_one)
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 20 40 60
[3,] 30 60 90
精彩评论