Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

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 ?

like image 309
Sj Bq Avatar asked Nov 07 '12 06:11

Sj Bq


People also ask

How do I add new values to a list in R?

To append an element in the R List, use the append() function. You can use the concatenate approach to add components to a list. While concatenate does a great job of adding elements to the R list, the append() function operates faster.

What does list () do in R?

The list() function in R is used to create a list of elements of different types. A list can contain numeric, string, or vector elements.


1 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
like image 141
Sven Hohenstein Avatar answered Oct 01 '22 03:10

Sven Hohenstein