To add new value in every element in list in R?

here is list1 , only tow elements--" name " and " age " in it,there are two value in every element ,now i want to add new value in every element,

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

is there more simple way to do ?


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

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

It depends a bit on what you want to do. If you want to add a different value to each element in the list, I think the easiest way is:

Vec <- c("herry",17,...)
i=0 
list1 <- lapply(list1, function(x) {i=i+1 ; append(x,Vec[i])})

If every vector in your list has the same length, then there's some shortcuts you can use too. If you want to add the same value to every element in the list:

list1 <- lapply(list1, function(x) append(x, "NewEl"))
链接地址: http://www.djcxy.com/p/65724.html

上一篇: 正确解码zip条目文件名称

下一篇: 在R中列表中的每个元素中添加新值?