0

As my question was marked as duplicate, let me ask it in another way. Imagine, that I ask you: what will be printed out by this code:

y <- list(c('hello','world'), c('good','morning'))
z <- paste(y, sep = '')
print(z)

If you don't know what will be, how can you get answer using R-docs? Is there a way to get answer without runinng code?

First version of my question is: My code is:

y <- list(c('hello','world'), c('good','morning'))
z <- paste(y, sep = '')
print(z)
[1] "c(\"hello\", \"world\")"  "c(\"good\", \"morning\")"

My question is why output of paste() has such pieces like "c(\" and ")", and how can I remove them?

  • 1
    Ooh...this is one of my favorite duplicates I think...! – joran Sep 28 '16 at 16:21
  • 2
    As noted above, while the duplicate linked to doesn't mention `paste`, the issue arises as soon as `paste` calls `as.character` on your list. – joran Sep 28 '16 at 16:23
  • 1
    As for the OP's actual intent, maybe `lapply(y,paste,collapse = " ")` is a better option? – joran Sep 28 '16 at 16:34
  • Regarding your edit asking about the R-docs: The documentation for `paste` tells you it will convert its arguments with `as.character`, and then concatenate them term by term. Since you only supplied the one argument `y`, there was nothing to concatenate it with, so `paste` just produces the result of calling `as.character(y)`. So yes, one could in principle understand this from just reading the documentation - but most people will learn more easily if they also try things out and see for themselves. – Tim Goodman Sep 29 '16 at 20:08

1 Answers1

0

You need to use do.call for applying a function to a list

y <- list(c('hello','world'), c('good','morning'))
z <- do.call(paste,args=c(y,sep = ''))
print(z)
Morgan Ball
  • 760
  • 9
  • 23