【发布时间】:2020-05-12 05:38:05
【问题描述】:
g = list(vegetable ="carrot", food=c("steak", "eggs"), numbers = c(4,2,1,7))
想知道如何在食物中添加其他元素吗? 尝试做食物
【问题讨论】:
-
g[["food"]] <- c(g[["food"]], "asparagus")。请参阅?"["进行冗长且技术性但有用的讨论。
g = list(vegetable ="carrot", food=c("steak", "eggs"), numbers = c(4,2,1,7))
想知道如何在食物中添加其他元素吗? 尝试做食物
【问题讨论】:
g[["food"]] <- c(g[["food"]], "asparagus")。请参阅 ?"[" 进行冗长且技术性但有用的讨论。
g[["food"]] <- c(g[["food"]], "asparagus")
【讨论】:
使用purrr 的一个选项可能是:
modify_in(g, "food", ~ c(., "asparagus"))
$vegetable
[1] "carrot"
$food
[1] "steak" "eggs" "asparagus"
$numbers
[1] 4 2 1 7
【讨论】:
我们可以使用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
【讨论】:
基础 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
【讨论】: