连接字符串

Sta*_*t-R 9 r string-concatenation

我有一个包含多个变量的数据框.我想要的是使用(串联)变量名创建一个字符串,但在它们之间还有其他东西......

这是一个简化的例子(变量的数量减少到只有3,而我实际上有很多)

编制一些数据框

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

实际代码......

  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
Run Code Online (Sandbox Code Playgroud)

这给...

[1] "The locations that we are considering are"
[2] "Location1"                          
[3] "Location2"                          
[4] "Location3 ."
Run Code Online (Sandbox Code Playgroud)

但我想要

我们正在考虑的位置是Location1,Location2和Location3.

我相信有一个更简单的方法,有些人会知道...谢谢你的时间......

cbe*_*ica 22

你在寻找这个collapse论点paste吗?

> paste (letters [1:3], collapse = " and ")
[1] "a and b and c"
Run Code Online (Sandbox Code Playgroud)


Bri*_*ggs 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="")
Run Code Online (Sandbox Code Playgroud)

这给了

> cat(string1)
The locations that we are considering are Location1, Location2 and Location3.
Run Code Online (Sandbox Code Playgroud)

请注意,如果只有1个元素,这将不会给出合理的英语strs.

我们的想法是在它们之间用逗号空间折叠除最后一个字符串之外的所有字符串,然后将它与样板文本和最后一个字符串一起粘贴.