marvinjonathcn
marvinjonathcn

Reputation: 67

R : How to join several lists of a single element into a single list of an element

I need to join several elements of a list (each of the elements is a long character), in a single list also of a character.

mylist <- list("values 10 15 25 30 35 36 36", "values 10 17 75 35 45 36 76")

mylist

[[1]]
[1] "values 10 15 25 30 35 36 36"

[[2]]
[1] "values 10 17 75 35 45 36 76"

The result I hope to get is:

mylist2 <- list("values 10 15 25 30 35 36 36 10 17 75 35 45 36 76")

mylist2

[[1]]
[1] "values 10 15 25 30 35 36 36 10 17 75 35 45 36 76"

I need it to work for lists with more than 2 items.

Upvotes: 0

Views: 51

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269644

Paste the components together giving a plain string, remove space followed by the word values and then turn that into a one component list:

list(gsub(" values", "", do.call("paste", mylist)))

If values could be any purely alphabetic single word then replace " values" with " [[:alpha:]]+" in the code above.

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101383

paste0("values ",gsub(".*?(\\d+.*)","\\1",mylist), collapse = " ") can give what you want

> paste0("values ",gsub(".*?(\\d+.*)","\\1",mylist), collapse = " ")
[1] "values 10 15 25 30 35 36 36 values 10 17 75 35 45 36 76"

Upvotes: 0

Related Questions