用逗号分隔列表,用“和”分隔最后一个元素

时间:2017-02-25 13:07:19

标签: r concatenation

我正试图找到一个简单的方法来分离动态变化列表(被动对象)的元素。问题是当“列表”只有一个元素时,我在字符串前面有一个不需要的“和”。所以,我想要一个简单的代码,当我有一个元素时不要添加“和”。

list<-c("something")
list<-c("something","something")
list<-c("something","something","something") 

paste0(c(paste(head(list, n=length(list) -1), collapse = ", ") , 
       "and",paste(tail(list, n=1) ) ), collapse= " " )

[1] " and something" # not what is expected
[1] "something and something" # ok
[1] "something, something and something" #ok

4 个答案:

答案 0 :(得分:2)

我们可以将subpaste

一起使用
fPaste <- function(vec) sub(",\\s+([^,]+)$", " and \\1", toString(vec))


fPaste("something")
#[1] "something"

fPaste(c("something","something"))
#[1] "something and something"

fPaste(c("something","something","something") )
#[1] "something, something and something"

fPaste(c("something","something","something", "something") )
#[1] "something, something, something and something"

答案 1 :(得分:1)

还有另一种方式:

i <- length(list)
if (i <= 1) {
  as.character(list)
} else {
  paste0(paste0(list[1:(i - 1)], collapse = ", "), " and ", list[i])
}

答案 2 :(得分:0)

我认为你需要一些逻辑来检测你的向量是否有多个元素,所以像:

## Note I've change list to x since its
## confusing, as it's actually a vector
if(length(x) > 1) " and " else ""

这给出了

paste0(c(
  paste(x[-length(x)], collapse = ", ") , 
         if(length(x) > 1) " and " else "", 
         x[length(x)]
         ), collapse= "" )

答案 3 :(得分:0)

我以前使用过一个(其他)现有函数,但不记得是哪个函数,但是这很好用,我总是使用 knitr!希望我以后记得。

knitr::combine_words(c("something"))
<块引用>

东西

knitr::combine_words(c("something","something"))
<块引用>

某事和某事

knitr::combine_words(c("something","something","something"))
<块引用>

某事,某事,某事