Aureliano Guedes
Aureliano Guedes

Reputation: 785

Concat named list of vectors

I'd trying to figure out how to transform a named list where the values are also list in a named list where the value is the result of a concatenation of the values within a vector.

I do not know if I explain correctly or easily, so follow the example.

x <- list(A = c("e", "f", "g"), B = c("a", "b", "c"), C = c("m", "l", "w"))

#$A
#[1] "e" "f" "g"
#$B
#[1] "a" "b" "c"
#$C
#[1] "m" "l" "w"

named_list_concat <- function(data){ ... }

named_list_concat(x)

#$A
#[1] "efg"
#$B
#[1] "abc"
#$C
#[1] "mlw"

Upvotes: 1

Views: 42

Answers (1)

tmfmnk
tmfmnk

Reputation: 40131

One base possibility:

lapply(x, function(x) paste(x, collapse = ""))

$A
[1] "efg"

$B
[1] "abc"

$C
[1] "mlw"

Or the same thing in a shortened form:

lapply(x, paste, collapse = "")

Upvotes: 1

Related Questions