我对粘贴感到困惑,并认为它只是简单的连接。
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?
此外,为什么会
results <-paste(whales[1], quails[1], collapse = '')
返回
“C D”?
有空格吗?
谢谢, d
修改
好的,我明白了
results <-paste(whales, quails, collapse = NULL, sep='')
会得到我想要的,但解释为什么以前的代码不起作用?还要感谢回答者。
答案 0 :(得分:23)
对于第一个问题,请尝试以下方法(这可能比选择重复2个字符更具说明性。)
### 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"
您真正想要做的是(获得“期望的”结果)如下:
### "Desired" result:
paste(whales, quails, sep = '', collapse = ' ')
[1] "CD DD CD DD DD"
请注意,我们正在为不同的值指定sep
和collapse
个参数,这与您的第二个问题有关。 sep
允许每个术语用字符串分隔,而collapse
允许整个结果用字符串分隔。
尝试
paste(whales, quails, collapse = '', sep = '')
[1] "CDDDCDDDDD"
或者,使用快捷paste0
,默认为paste
sep = ''
paste0(whales, quails, collapse = '')
答案 1 :(得分:0)