Reorder words in each element of a vector

最后都变了- 提交于 2019-12-24 00:27:04

问题


I'd like to change the word order for each element in a vector. Specifically I'd like to make another vector where the first word is now the last word for a number of elements that differ in length.


Data

metadata1 <- c("reference1 an organism", 
               "reference2 another organism here",
               "reference3 yet another organism is here")

Desired outcome

metadata2 <- c("an organism reference1", 
               "another organism here reference2",
               "yet another organism is here reference3")

My attempt

metadata2 <- lapply(strsplit(metadata1," "), function(x) paste(x[c(2,3,4,5,1)]))



I've tried to use lapply() to separate each element by spaces using strsplit(), and then paste them back together using the order index. This gets the words in the right order, but returns a list where the words are separate elements and because some elements are longer than others I get "NA"s when an index number is higher than the number of words in that element. I've also tried sapply() which returns a matrix and tapply() which does not work.



回答1:


library(stringr)
paste(word(metadata1,2, -1), word(metadata1,1), sep = " ")
# [1] "an organism reference1"                 
# [2] "another organism here reference2"       
# [3] "yet another organism is here reference3"

# OR

sapply(metadata1, function(x){ y = unlist(strsplit(x, " "))
                           paste(c(y[-1],y[1]),collapse = " ")
                           })


# OR ( this is purely @Frank's answer)( Shall remove when he puts it as an answer)
sub("^(\\w+) (.*)$", "\\2 \\1", metadata1)


来源:https://stackoverflow.com/questions/42009315/reorder-words-in-each-element-of-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!