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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With