Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply paste over a list of vectors to get a list of strings

Tags:

r

This seems so simple but no matter which *apply function I use, the correct answer eludes me. I haven't tried any other package because it seems *apply should definitely be able to do this.

My data:

data = list(foo=c("first", "m", "last"), bar=c("first", "m", "last"))

What I really think should work:

lapply(data, FUN=paste)

But it gives me:

$foo
[1] "first" "m"     "last" 

$bar
[1] "first" "m"     "last" 

I want:

$foo
[1] "first m last"
$bar
[1] "first m last"

Of course I've tried a whole slew of other stuff:

> paste(data)
[1] "c(\"first\", \"m\", \"last\")" "c(\"first\", \"m\", \"last\")"
> paste(data, collapse = "")
[1] "c(\"first\", \"m\", \"last\")c(\"first\", \"m\", \"last\")"
> paste(data, sep = "")
[1] "c(\"first\", \"m\", \"last\")" "c(\"first\", \"m\", \"last\")"
> paste(data, collapse = "", sep="")
[1] "c(\"first\", \"m\", \"last\")c(\"first\", \"m\", \"last\")"
> paste(as.vector(data), collapse = "", sep="")
[1] "c(\"first\", \"m\", \"last\")c(\"first\", \"m\", \"last\")"
> paste(c(data), collapse = "", sep="")
[1] "c(\"first\", \"m\", \"last\")c(\"first\", \"m\", \"last\")"
> paste(c(data, recursive = T), collapse = "", sep="")
[1] "firstmlastfirstmlast"

I don't understand where this quoted "c" nonsense is coming from.

like image 730
Matt Chambers Avatar asked Apr 18 '15 22:04

Matt Chambers


1 Answers

Your initial approach was almost correct, you just need to add collapse = " " in order to concatenate the vectors into one string in each element of your list

lapply(data, paste, collapse = " ") 
# $foo
# [1] "first m last"
# 
# $bar
# [1] "first m last"
like image 195
David Arenburg Avatar answered Sep 20 '22 21:09

David Arenburg