I want to create an empty list so I can replace its elements with other lists.
For example
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!
You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.
To add an item to a list in R programming, call append() function and pass the list and item as arguments in the function call.
The list is one of the most versatile data types in R thanks to its ability to accommodate heterogenous elements. A single list can contain multiple elements, regardless of their types or whether these elements contain further nested data. So you can have a list of a list of a list of a list of a list …
Just change
results[1] = test_function(seedX = seeds[1])
to
results[[1]] <- test_function(seedX = seeds[1])
The important change is the [...]
element indexing operator to the [[...]]
list component indexing operator, as you need to assign the list component to the 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 follow the R convention, but also because =
means something different (and therefore can't be used for assignments) in other contexts, such as named parameter specifications in function calls, so using <-
allows for more consistency.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With