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