Question

I have a function that is applied to a dataframe (below I refer to this as function1name). There are multiple outputs of the function that are saved in a list.

Inside the function is a constant (cval). I would like to run the function on the same dataframe multiple times using a number of different constant values (e.g. between 1 and 5 or between 1 and 100). For each run of the function, I would like to save the results in a list.

This is what I've tried:

newfunction<-function (df)
{
for(i in 1:5)  #this could be 1:10, 1:100 etc. but I'm just trying 1:5 for now
{robj<-list(function1name(df, cval=i)) #function1name is the function with the constant
}
}

newfunction(df)

The issue with this is that it only saves the last run of the function1name in my object robj. i.e. in the above, it only saves the performing of function1name when cval=5. I want to save in a list runs of that function when cval=1,2,3,4 and 5.

Any help appreciated.

Was it helpful?

Solution

A list could contain list elements as well. So you can just use the same approach for multiple constants:

cval <- 1:10
l <- vector(mode = "list", length = length(cval)

for (i in seq(along=cval)) {
  l[[i]] <- list(function1name(df, cval=cval[i]))
}

Or you could use lapply:

cval <- 1:10
l <- lapply(cval, function1name, df = df)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top