将字符串添加到列表中向量的末尾时遇到麻烦

问题描述 投票:2回答:4
g = list(vegetable ="carrot", food=c("steak", "eggs"), numbers = c(4,2,1,7))

想知道如何在食物中添加其他元素吗?尝试做食物

r list vector append
4个回答
5
投票
g[["food"]] <- c(g[["food"]], "asparagus")

3
投票

利用purrr的一个选项可能是:

modify_in(g, "food", ~ c(., "asparagus"))

$vegetable
[1] "carrot"

$food
[1] "steak"     "eggs"      "asparagus"

$numbers
[1] 4 2 1 7

1
投票

我们可以使用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

或使用modifyList中的base R

modifyList(g, list(food = c(g[['food']], 'asparagus')))
#$vegetable
#[1] "carrot"

#$food
#[1] "steak"     "eggs"      "asparagus"

#$numbers
#[1] 4 2 1 7

0
投票

基础R解决方案

g <- within(g,food <- c(food,"asparagus"))

g <- within(g,food <- append(food,"asparagus"))

诸如此类

> g
$vegetable
[1] "carrot"

$food
[1] "steak"     "eggs"      "asparagus"

$numbers
[1] 4 2 1 7
© www.soinside.com 2019 - 2024. All rights reserved.