Bharat Desai
Bharat Desai

Reputation: 123

How to append to a list from multiple list in r?

I have 4 lists: 3 equally sized filled lists and 1 empty list, for example:

list1<-as.list(c(1:10))
list2<-as.list(c(101:110))
list3<-as.list(c(1001:1010))
list4<-list()

I want to append the ith element of each of the first 3 lists into the 4th list. list 4 should look like:

[1,101,1001,2,102,1002,....,10,110,1010]

How do i go about doing this? My code currently looks like this:

for (i in length(list1)){
  local({
    i<-i
    list4.append(list1[i])
    list4.append(list2[i])
    list4.append(list3[i])

  })
}

but i receive the error:

could not find function "list4.append"

Upvotes: 4

Views: 5895

Answers (2)

cderv
cderv

Reputation: 6542

Using the approach you have on a for-loop, it need some adjustement.

list1<-as.list(c(1:10))
list2<-as.list(c(101:110))
list3<-as.list(c(1001:1010))
list4<-list()

for (i in seq_along(list1)){
    list4 <<- append(list4, list1[i])
    list4 <<- append(list4, list2[i])
    list4 <<- append(list4, list3[i])
}
  • Don't use local, otherwise you won't be able to modify list4
  • use <<- to assign to list4 outside the for loop
  • append is a function you assign on an object. It can't be called python-like as a method of the object obj.method

Whereas For-loop are what we can be used to, in R it is better to avoid them when possible.


Another solution is to use the purrr package that helps dealing with list and functional programming. You could get you results with

library(purrr)
pmap(list(list1, list2, list3), c) %>% simplify()
#>  [1]    1  101 1001    2  102 1002    3  103 1003    4  104 1004    5  105
#> [15] 1005    6  106 1006    7  107 1007    8  108 1008    9  109 1009   10
#> [29]  110 1010

pmap applies a function to each element of the lists in order. (1rst of list1, list2 and list3, then 2nd of list1, list2, list3, ...) simplify is here to get a vector at the end, _simplifying the list result.

Upvotes: 1

Prem
Prem

Reputation: 11955

You can use mapply to combine multiple lists into one. The function used within mapply is c

list4 <- mapply(c, list1, list2, list3, SIMPLIFY = F)

Sample data:

list1 <- as.list(c(1:10))
list2 <- as.list(c(101:110))
list3 <- as.list(c(1001:1010))

Upvotes: 3

Related Questions