将字符串向量连接成一个字符串 - 对于 df 中的每一行

concatenate vector of strings into a single string - for each row in df

这可能很简单,但我找不到解决方案。 我有一个 df 字符串,例如:

data <- data.frame(x1 = c("abc", "", "de"), 
                   x2 = c("fghi", "j", "kl"), 
                   x3 = c("m", "", ""))
> data                                       
  x1   x2  x3
1 abc      de
2 fghi j   kl
3 m

我想将每一行连接成一个字符串,以便输出只有一列:

> data
  x1
1 abc de
2 fghi j kl
3 m

我试过了

apply(data, 2, paste)

但它不起作用,stringr::str_c 的任何变体也不起作用。 有什么想法吗?

如何使用 paste,与 sep = " " :

data$new_col <- paste(data$x1, data$x2, data$x3, sep = " ")

require(stringr)
data <- within(data,  new_col <- paste(x1, x2, x3, sep=" ")

data$new_col <- as.character(interaction(data,sep=" "))

interaction returns a factor 这就是为什么我转换为 as.character

所有 3 种方式都会让你:

   x1   x2 x3    new_col
1 abc fghi  m abc fghi m
2        j            j 
3  de   kl        de kl 

您接近正确的代码,只需添加折叠并处理 margin=1 的行:

apply(data, 1, paste,collapse=" ")
[1] "abc fghi m" " j "        "de kl "

来自文档

collapse an optional character string to separate the results.

要将输出整合到您的数据集中:

data$pasted<-apply(data, 1, paste,collapse=" ")
> data
   x1   x2 x3     pasted
1 abc fghi  m abc fghi m
2        j            j 
3  de   kl        de kl 

加上 dplyr,使用 str_c() 的一种方法是:

data %>%
 rowwise() %>%
 transmute(x1 = str_c(c_across(everything()), collapse = " "))

  x1          
  <chr>       
1 "abc fghi m"
2 " j "       
3 "de kl "