[R] apply function to multiple list arguments

Carlos Nasher carlos.nasher at googlemail.com
Tue Oct 14 20:42:30 CEST 2014


Hi R helpers,

I'm struggling how to apply a function to multiple lists. My function uses
a dataframe, a list of parameters and a fixed value as arguments. Now I
want to apply that function to several dataframes contained in list, with
several lists of parameters (also contained in a list) and the fixed value.
Here's an example:


#####

fix <- 2 # fixed value

x <- c(1,2,3)
y <- c(4,5,6)

df_1 <- data.frame(x,y) # first dataframe
df_2 <- 2*df_1 # second dataframe

list_df <- list(df_1,df_2) # list containing dataframes

par_1 <- list(a=5,b=10) # first list of parameters
par_2 <- list(a=6,b=11) # second list of parameters

list_par <- list(par_1,par_2) # list of lists of parameters

f <- function(data,params,z){
  res <- (data$x*params$a+data$y*params$b)*z
  return(res)
}

res_1 <- f(data = df_1, params = par_1, z = fix) # result of applying
function to first dataframe and first list of parameters
res_2 <- f(data = df_2, params = par_2, z = fix) # result of applying
function to second dataframe and second list of parameters

#####

I got the list of dataframes and parameters from a former use of lapply. I
was hoping to get the desired results (res_1, res_2) again in a list. I
tried mapply, but I don't get it running. Can anybody help?

Thanks and best regards,
Carlos



-- 
-----------------------------------------------------------------
Carlos Nasher
Buchenstr. 12
22299 Hamburg

tel:            +49 (0)40 67952962
mobil:        +49 (0)175 9386725
mail:          carlos.nasher at gmail.com

	[[alternative HTML version deleted]]



More information about the R-help mailing list