Create an empty list to populate it with lists in R

I want to create an empty list to replace its elements with other lists.

for instance

simulations = 10 seeds = sample(10000:99999, simulations, replace=F) test_function <- function(seedX){ lista = list(seedX=seedX, dataframe=data.frame(x=runif(10, -5.0, 5.0),y=rnorm(10,mean = 0,sd = 1))) return(lista) } results <- vector("list", simulations) results[1] = test_function(seedX = seeds[1]) 

I get the following error:

 Warning message: In results[1] = test_function(seedX = seeds[1]) : number of items to replace is not a multiple of replacement length 

What am I doing wrong?

Thanks!

+6
source share
1 answer

Just change

 results[1] = test_function(seedX = seeds[1]) 

to

 results[[1]] <- test_function(seedX = seeds[1]) 

An important change is the element indexing operator [...] for the element list indexing operator [[...]] , since you need to assign the list component to a new list. See https://stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.html .

(You should also use the assignment operator <- instead of = , mainly to fulfill the R convention, but also because = means something else (and therefore cannot be used for assignments) in other contexts, such as named parameter specifications in function calls, so using <- allows for more consistency.)

+7
source

Source: https://habr.com/ru/post/984334/


All Articles