我想更改向量中每个元素的词序。具体来说,我想制作另一个向量,其中第一个单词现在是许多长度不同的元素的最后一个单词。
Data
metadata1 <- c("reference1 an organism",
"reference2 another organism here",
"reference3 yet another organism is here")
期望的结果
metadata2 <- c("an organism reference1",
"another organism here reference2",
"yet another organism is here reference3")
我的尝试
metadata2 <- lapply(strsplit(metadata1," "), function(x) paste(x[c(2,3,4,5,1)]))
我尝试过使用lapply()
使用空格分隔每个元素strsplit()
,然后使用顺序索引将它们粘贴回一起。这会以正确的顺序获取单词,但会返回一个列表,其中单词是单独的元素,并且由于某些元素比其他元素长,因此当索引号高于该元素中的单词数时,我会得到“NA”。我也尝试过sapply()
它返回一个矩阵和tapply()
这是行不通的。
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)