MathsIsHard
MathsIsHard

Reputation: 277

How to Store Data in a List - R

I hope someone can be of help here.

I'm using R and I've reached a situation where I need to store returned data from a function, the data is in the form a vector. So for example, the function may return:

c(1,2,3,4,5)

Suppose I have a list I have already created before:

#I have to store 10 values
alpha = list(rep(NA, 10))

How can I store the returned vector in my list? For example, something along the lines of:

alpha[1] = c(1,2,3,4,5)

So then:

alpha = (c(1,2,3,4,5), NA, NA, NA, NA, NA, NA, NA, NA, NA)

Any help will be appreciated, thanks.

Upvotes: 0

Views: 10215

Answers (1)

cole
cole

Reputation: 1757

It seems like you may have some learning to do about lists. They are a powerful feature in R (more reading) The apply family (lapply and mapply, etc.) can often help you avoid this sort of behavior in general. But to answer your question:

alpha <- as.list(rep(NA, 10))

alpha[[1]] <- c(1, 2, 3, 4, 5)

print(alpha)
#> [[1]]
#> [1] 1 2 3 4 5
#> 
#> [[2]]
#> [1] NA
#> 
#> [[3]]
#> [1] NA
#> 
#> [[4]]
#> [1] NA
#> 
#> [[5]]
#> [1] NA
#> 
#> [[6]]
#> [1] NA
#> 
#> [[7]]
#> [1] NA
#> 
#> [[8]]
#> [1] NA
#> 
#> [[9]]
#> [1] NA
#> 
#> [[10]]
#> [1] NA

A simple example of using lapply:

myfunc <- function(input) {
  return(input + 10)
}

lapply(1:10, myfunc)
#> [[1]]
#> [1] 11
#> 
#> [[2]]
#> [1] 12
#> 
#> [[3]]
#> [1] 13
#> 
#> [[4]]
#> [1] 14
#> 
#> [[5]]
#> [1] 15
#> 
#> [[6]]
#> [1] 16
#> 
#> [[7]]
#> [1] 17
#> 
#> [[8]]
#> [1] 18
#> 
#> [[9]]
#> [1] 19
#> 
#> [[10]]
#> [1] 20

Also, it is helpful to know that the [ operator returns a list while the [[ operator returns the element of a list. (And the same applies for replacement)

To answer your follow-up question: list tries to define a list (i.e. something like list(obj,obj2,obj3)), whereas as.list tries to convert an object to a list. Since rep() creates a vector, list(rep()) gives you a list of length one (with the output of rep() inside the first element). When you want the vector presented as a list, as.list is the way to go.

Upvotes: 2

Related Questions