g = list(vegetable ="carrot", food=c("steak", "eggs"), numbers = c(4,2,1,7))
想知道如何在食物中添加其他元素吗?尝试做食物
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