我已经尝试过搜索这个并确定答案在那里,但没有运气。
我尝试使用stringr
包,但让它从右到左读取文本行。
library(stringr)
fruits <- c("apples and oranges and pears and bananas", "pineapples and mangos and guavas")
str_split_fixed(fruits, " and ", 3)
返回:
"apples" "oranges" "pears and bananas"
"pineapples" "mangos" "guavas"
我试图让它返回:
"apples and oranges" "pears" "bananas"
"pineapples" "mangos" "guavas"
答案 0 :(得分:3)
它可能不在基础,stringr
或stringi
,但你可以自己实现它:
sapply(stri_split_fixed(stri_reverse(fruits), " dna ", 3)[[1]], stri_reverse, USE.NAMES=FALSE)
## [1] "bananas" "pears" "apples and oranges"
,对于您的大型示例数据:
fruits <- c("apples and oranges and pears and bananas",
"pineapples and mangos and guavas")
do.call(rbind, lapply(stri_reverse(fruits), function(x) {
rev(sapply(stri_split_fixed(x, " dna ", 3)[[1]], stri_reverse, USE.NAMES=FALSE))
}))
## [,1] [,2] [,3]
## [1,] "apples and oranges" "pears" "bananas"
## [2,] "pineapples" "mangos" "guavas"
此外,理查德改编的修改版本:
matrix(rev(stri_reverse(str_split_fixed(stri_reverse(fruits),
stri_reverse(" and "), 3))),
nrow=length(fruits), ncol=3, byrow=TRUE)
效率更高。