Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65902155/concatenate-vector-of-strings-into-a-single-string-for-each-row-in-df

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...