Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create an empty list to fill it up with lists in R

Tags:

r

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!

like image 211
Ignacio Avatar asked Mar 27 '15 18:03

Ignacio


People also ask

How do I make a list of empty lists?

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.

How do I append a list to a list in R?

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.

Can you have lists of lists in R?

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 …


1 Answers

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.)

like image 52
bgoldst Avatar answered Oct 26 '22 12:10

bgoldst