To add a new value to each list item in R?

here is list1 , it has only towing elements - < name "and" age ", each element has two values, now I want to add a new value to each 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 an easier way to do this?

+6
source share
2 answers

This solution works for lists of any length:

 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 
+4
source

It depends on what you want to do. If you want to add a different value for each item 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 each vector in your list has the same length, then there are several shortcuts that you can also use. If you want to add the same value to each item in the list:

 list1 <- lapply(list1, function(x) append(x, "NewEl")) 
0
source

All Articles