Reputation: 77
g = list(vegetable ="carrot", food=c("steak", "eggs"), numbers = c(4,2,1,7))
Was wondering how to add another element in food? Tried doing food <- asparagus but that didn't work
Upvotes: 3
Views: 75
Reputation: 102880
A base R solution
g <- within(g,food <- c(food,"asparagus"))
or
g <- within(g,food <- append(food,"asparagus"))
such that
> g
$vegetable
[1] "carrot"
$food
[1] "steak" "eggs" "asparagus"
$numbers
[1] 4 2 1 7
Upvotes: 0
Reputation: 887951
We can use map_if
library(purrr)
map_if(g, names(g) == 'food', ~ c(.x, 'asparagus'))
#$vegetable
#[1] "carrot"
#$food
#[1] "steak" "eggs" "asparagus"
#$numbers
#[1] 4 2 1 7
Or with modifyList
from base R
modifyList(g, list(food = c(g[['food']], 'asparagus')))
#$vegetable
#[1] "carrot"
#$food
#[1] "steak" "eggs" "asparagus"
#$numbers
#[1] 4 2 1 7
Upvotes: 2
Reputation: 40171
One option utilizing purrr
could be:
modify_in(g, "food", ~ c(., "asparagus"))
$vegetable
[1] "carrot"
$food
[1] "steak" "eggs" "asparagus"
$numbers
[1] 4 2 1 7
Upvotes: 2