Paste/Collapse in R

主宰稳场 提交于 2019-11-27 22:14:28

For the first question, try the following (which might be more illustrative than choosing to repeat 2 characters).

### Note that R paste's together corresponding elements together...
paste(c("A", "S", "D", "F"), 
      c("W", "X", "Y", "Z"))

[1] "A W" "S X" "D Y" "F Z"

### Note that with collapse, R converts the above 
  # result into a length 1 character vector.
paste(c("A", "S", "D", "F"), 
      c("W", "X", "Y", "Z"), collapse = '')

[1] "A WS XD YF Z"

What you really want to do (to get the "desired" result) is the following:

### "Desired" result:
paste(whales, quails, sep = '', collapse = ' ')

[1] "CD DD CD DD DD"

Note that we are specifying the sep and collapse arguments to different values, which relates to your second question. sep allows each terms to be separated by a character string, whereas collapse allows the entire result to be separated by a character string.

Try

paste(whales, quails, collapse = '', sep = '')

[1] "CDDDCDDDDD"

Alternatively, use a shortcut paste0, which defaults to paste with sep = ''

paste0(whales, quails, collapse = '')

For those who like visuals, here is my take at explaining how paste works in R:

sep creates element-wise sandwich stuffed with the value in the sep argument:

collapse creates ONE big sandwich with the value of collapse argument added between the sandwiches produced by using the sep argument:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!