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

Viewed 293

This may be an easy one but I could not find a solution. I have a df of strings, for example:

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

I want to concatenate each row into a single string, so that the output only has one column:

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

I tried

apply(data, 2, paste)

but it doesn't work, and neither does any variation of stringr::str_c. any thoughts?

3 Answers

How about using paste, with sep = " " :

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

Or

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

Or

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

interaction returns a factor that's why i convert to as.character

All 3 ways will get you:

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

You are close to the right code, just add collapse and work on rows with margin=1:

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

from documentation

collapse an optional character string to separate the results.

To integrate the output in your dataset:

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 

With the additon of dplyr, one way to use str_c() could be:

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

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