在R中粘贴/折叠 [英] Paste/Collapse in R
问题描述
我对粘贴感到困惑,并认为这只是简单的串联。
I'm confused by paste, and thought it was just simple concatenating.
whales <- c("C","D","C","D","D")
quails <- c("D","D","D","D","D")
results <-paste(whales, quails, collapse = '')
为什么会返回 C DD DC DD DD D而不是CD DD CD DD DD?
Why would this return "C DD DC DD DD D" instead of CD DD CD DD DD?
此外,为什么会
results <-paste(whales[1], quails[1], collapse = '')
返回
CD吗?
有空格?
谢谢,
D
Thanks, D
EDIT
好的,我看到
results <-paste(whales, quails, collapse = NULL, sep='')
会得到我想要的信息,但是解释了为什么以前代码不起作用?还要感谢回答者。
will get me what I want, but an explanation of why the previous code didn't work? And also thank you to the answerers.
推荐答案
对于第一个问题,请尝试以下操作(与选择重复2个字符)。
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"
请注意,我们指定的是 sep
和崩溃
不同值的参数,这与您的第二个问题有关。 sep
允许将每个术语用字符串分隔,而 collapse
允许将整个结果用字符分隔
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.
尝试
paste(whales, quails, collapse = '', sep = '')
[1] "CDDDCDDDDD"
或者,使用快捷方式 paste0
,该快捷方式默认为 paste
,其中 sep =''
Alternatively, use a shortcut paste0
, which defaults to paste
with sep = ''
paste0(whales, quails, collapse = '')
这篇关于在R中粘贴/折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!