Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new element to list of lists (in R)

Tags:

list

r

I create a list of lists in the following way:

 key<-112233
 list1 <- list(a = 2, b = 3)
 list2 <- list(c = "a", d = "b")
 mylist <- list(list1, list2)

Then, I want to add a new pair to the second list but I would like to key to be the value of key defined earlier. When I do

 mylist[[2]]$key<-6

I get

$c
[1] "a"

$d
[1] "b"

$key
[1] 6

rather than

$c
[1] "a"

$d
[1] "b"

$112233
[1] 6

I have tried using get or many possible other combinations using [] or [[]] but nothing seems to work. Please advice.

like image 748
g_puffo Avatar asked May 17 '15 22:05

g_puffo


1 Answers

key<-"112233"
list1 <- list(a = 2, b = 3)
list2 <- list(c = "a", d = "b")
mylist <- list(list1, list2)
mylist[[2]][key]<-6

[[1]]
[[1]]$a
[1] 2

[[1]]$b
[1] 3


[[2]]
[[2]]$c
[1] "a"

[[2]]$d
[1] "b"

[[2]]$`112233`
[1] 6

Update as per the comment from @user20650: Rather than converting variable key to string in the beginning, you can also do:

mylist[[2]][as.character(key)] <- 6
like image 98
user227710 Avatar answered Oct 22 '22 21:10

user227710