R is applied with several parameters

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 L * list with exits

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

How to do this with apply , mapply or lapply ?

+106
r
Jul 26 2018-11-11T00:
source share
4 answers

Just pass var2 as an optional argument to one of the functions you use.

 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 each myfxn call. If instead you want every call to myfxn get 1st / 2nd / 3rd / etc. element of both mylist and var2 , then you are in the mapply domain.

+159
Jul 26 '11 at 8:53
source share

If your function has two vector variables and needs to be calculated for each of their values ​​(as @Ari B. Friedman mentions), 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 
+32
Nov 01 '16 at 16:08
source share

To further generalize the @Alexander example, outer relevant in cases where the function must calculate itself for each pair of vector quantities:

 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 
0
Jul 08 '19 at 10:26
source share

I used RODBC to connect to an Oracle XE hr schema. I needed a function that could return the number of records in a table. So that...

 function(rodbcConnection, schemaName, tableName){ results <- sqlQuery(rodbcConnection, paste("SELECT * FROM ", schemaName, ".", tableName)) return(dim(results)[1]) } 

But how to apply this to a table name vector? Here is how.

 > x <- sapply(hrTableNames, noOfRecords, rodbcConnection=connection, schemaName="hr") 

Because sapply does its job by applying the noOfRecords function to each row of hrTableNames, R replaces the missing tableName parameter with the current iterative value of hrTableNames.

At last.

 > barplot(t(x), las=2) 
-3
Feb 23 '17 at 20:36
source share



All Articles