2017-02-25 90 views
2

我想要一個簡短的方法來分隔動態變化列表(反應對象)的元素。問題是當「列表」只有一個元素時,我在字符串之前有一個不需要的「and」。所以,我想要一個簡單的代碼,認爲當我有一個元素不添加「和」時。用逗號和最後一個元素與「和」分隔列表

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 
+0

根據示例不清楚你的預期是什麼。 'list'中有3個元素的向量。你的輸入數據是什麼?它是'paste0(....' – akrun

+0

列表可以有從1到幾個字符串。 – Ferroao

+0

好吧,但你期望什麼? – akrun

回答

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" 
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= "") 
1

而又另一種方式:

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