vintdeux
vintdeux

Reputation: 47

how to sort text value word by word

In my problem, each value of a vector is a text composed of multiple words. I try to sort word by word the text. I don't care to sort the vector. e.g.

vect <- c("tim is a man", "sam was a studend", "my young daughter")

how to get vect arranged like this :

"a is man tim"
"a sam student was"
"daughter my young"

Thanks for your help.

Upvotes: 0

Views: 55

Answers (1)

akrun
akrun

Reputation: 887128

We can split the string into substring and then do the sort

sapply(strsplit(vect, "\\s+"), function(x) paste(sort(x), collapse=' '))
#[1] "a is man tim"      "a sam studend was" "daughter my young"

Upvotes: 3

Related Questions