gpt4 book ai didi

r - 在R列表中的每个元素中添加新值?

转载 作者:行者123 更新时间:2023-12-01 22:39:32 25 4
gpt4 key购买 nike

这里是list1,里面只有两个元素——“name”和“age”,每个元素有两个值,现在我想在每个元素中添加新的值,

list1<-list(name=c("bob","john"),age=c(15,17))
list1
$name
[1] "bob" "john"

$age
[1] 15 17
list1[[1]][3]<-"herry"
list1[[2]][3]<-17
list1
$name
[1] "bob" "john" "herry"

$age
[1] 15 17 17

还有更简单的方法吗?

最佳答案

此解决方案适用于任何长度的列表:

values <- list("herry", 17) # a list of the new values
list1 <- mapply(append, list1, values, SIMPLIFY = FALSE)


# $name
# [1] "bob" "john" "herry"

# $age
# [1] 15 17 17

关于r - 在R列表中的每个元素中添加新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13263974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com