Anuj Amin
Anuj Amin

Reputation: 77

Having trouble adding a string to the end of a vector that's in a list

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

Answers (4)

ThomasIsCoding
ThomasIsCoding

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

akrun
akrun

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

tmfmnk
tmfmnk

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

Jakub.Novotny
Jakub.Novotny

Reputation: 3067

g[["food"]] <- c(g[["food"]], "asparagus")

Upvotes: 4

Related Questions