2012-03-22 223 views
9

我有一個數據框與幾個變量。我要的是創建一個使用(串聯)變量名的字符串,但在他們之間的其他什麼東西......連接字符串

下面是一個簡單的例子(一些變量縮小到只有3,而我其實有很多

彌補一些數據幀

df1 <- data.frame(1,2,3) # A one row data frame 
    names(df1) <- c('Location1','Location2','Location3') 

實際代碼...

len1 <- ncol(df1) 
    string1 <- 'The locations that we are considering are' 
    for(i in 1:(len1-1)) string1 <- c(string1,paste(names(df1[i]),sep=',')) 

    string1 <- c(string1,'and',paste(names(df1[len1]),'.')) 
    string1 

這給了...

[1] "The locations that we are considering are" 
[2] "Location1"       
[3] "Location2"       
[4] "Location3 ." 

但我想

我們正在考慮的地點是LOCATION1,LOCATION2和LOCATION3。

我肯定是有一些的,你會知道很多更簡單的方法... 謝謝你的時間......

回答

22

你正在尋找的pastecollapse說法?

> paste (letters [1:3], collapse = " and ") 
[1] "a and b and c" 
+0

對不起@ cbeleites我做了一些編輯你的答案 – 2012-03-22 15:41:30

+0

在這種情況下,'後貼( 「考慮」,粘貼(頭(地名(DF),-1) ,collapse =「,」),「and」,tail(names(df),1),「。」,sep =「」)。 – cbeleites 2012-03-22 15:48:49

2

如果你的主要目標是打印結果到屏幕(或其它輸出),然後使用cat功能(他的名字從串連派生):

> cat(names(iris), sep=' and '); cat('\n') 
Sepal.Length and Sepal.Width and Petal.Length and Petal.Width and Species 

如果您需要一個變量字符串,那麼你可以使用pastecollapse參數。 sprintf函數對於將字符串插入其他字符串(或將數字插入字符串)也很有用。

5

事實上,這些是data.frame的名稱並不重要,所以我已經將這部分拉出來並將它們分配給變量strs

strs <- names(df1) 
len1 <- length(strs) 
string1 <- paste("The locations that we are considering are ", 
       paste(strs[-len1], collapse=", ", sep=""), 
       " and ", 
       strs[len1], 
       ".\n", 
       sep="") 

這給

> cat(string1) 
The locations that we are considering are Location1, Location2 and Location3. 

注意,這不會給懂事英語如果只有1 strs元素。

這個想法是摺疊除了最後一個字符串之外的所有字符串,然後將它們與樣板文本和最後一個字符串粘貼在一起。

0

的其他選項是:

library(stringr) 
str_c("The location that we are consiering are ", str_c(str_c(names(df1)[1:length(names(df1))-1], collapse=", "), names(df1)[length(names(df1))], sep=" and "))