根据条件重新排列字符串中的单词

强尼

我有此数据:

df<- data.frame("position" = c("ante", "ex", "post", "post ante pre", "post pre", "ante post pre", "ex pre", "ante pre")) 

现在,我想移动单词“ pre”,使其成为字符串中的第一个单词,但仅适用于包含两个单词和单词“ pre”的字符串,因此行号1、2、3、4和6不应为受到影响。

结果应该是:

df <- data.frame("position" = c("ante", "ex", "post", "post ante pre", "pre post", "ante post pre", "pre ex", "pre ante"))

我想我可以从编写grepl语句开始,只选择包含单词“ pre”的行,但此后我有点迷路了。

克里斯

您可以为此使用正则表达式:

首先,我对您的示例进行了编辑,以使开始的结果和期望的结果有所不同(假设这是根据您编写的内容得出的期望结果)

library(dplyr)
library(stringr)


df <- data.frame("position" = c("ante", "ex", "post", "post pre ante", "post pre", "ante post pre", "ex pre", "pre ante")) 


df
#>        position
#> 1          ante
#> 2            ex
#> 3          post
#> 4 post pre ante
#> 5      post pre
#> 6 ante post pre
#> 7        ex pre
#> 8      pre ante
df2 <- data.frame("position" = c("ante", "ex", "post", "post pre ante", "pre post", "ante post pre", "pre ex", "pre ante"))
df2
#>        position
#> 1          ante
#> 2            ex
#> 3          post
#> 4 post pre ante
#> 5      pre post
#> 6 ante post pre
#> 7        pre ex
#> 8      pre ante


然后使用正则表达式:

df3 <- df %>%
  mutate(position = str_replace(position,'^([^\\s]+) {1}(?=pre$)(pre)','\\2 \\1'))

df3
#>        position
#> 1          ante
#> 2            ex
#> 3          post
#> 4 post pre ante
#> 5      pre post
#> 6 ante post pre
#> 7        pre ex
#> 8      pre ante

identical(df2, df3)
#> [1] TRUE

轻微编辑:我认为前瞻是不必要的,因此我们可以将其减少为:

df3 <- df %>%
  mutate(position = str_replace(position,'^([^\\s]+) {1}(pre)$','\\2 \\1'))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章