具有正则表达式的具有多个条件的一列转换

One column transformation with multiple conditions with regular expressions

我有一个数据框:

ID       value
1      he following object is masked from ‘package:purrr’
2      Attaching package: ‘magrittr’
3      package ‘ggplot2’ was built under R version 3.6.2
4      Warning messages:

这里是转换列值的代码:

df <- df %>% 
  mutate(value = stringr::str_replace(value, '(^he following object)', '\1'),
         value = stringr::str_replace(value, '(^Attaching package:)', '\1'),
         value = stringr::str_replace(value, '(^package ‘ggplot2’)', '\1'))
) %>%   
  group_by(ID, value) 

输出是:

ID       value
1      he following object
2      Attaching package: 
3      package ‘ggplot2’
4      Warning messages:

如您所见,我在一栏中多次使用 stringr::str_replace。我的实际数据要大得多(比如数百万行)。这只是一个子集示例。那么,我怎样才能将这三次使用一次这个功能结合起来呢?我想使用相同的函数和库(没有根本改变)

我试过了,但还是不行:

df <- df %>% 
  mutate(value = str_replace_all(value, '(^he following object).*|(^Attaching package:).*|(^package ‘ggplot2’).*', '\1')) %>%   
  group_by(ID, value)

它给了我这个:

ID       value
1      he following object’
2      
3     
4      Warning messages:

这是您要找的吗?

df %>% 
 mutate(value = stringr::str_replace_all(value, 
                                         c('(^he following object).*' = '\1',
                                           '(^Attaching package:).*'= '\1',
                                           '(^package ‘ggplot2’).*'= '\1')
                                         ))
#>   ID               value
#> 1  1 he following object
#> 2  2  Attaching package:
#> 3  3   package ‘ggplot2’
#> 4  4   Warning messages:

请注意,我必须添加 .*,因为您的代码对我不起作用。它没有替换整个句子。

您可以使用 str_extract 然后使用现有值 coalesce,而不是使用 str_replace 并使用反向引用捕获字符串。

library(dplyr)
library(stringr)

df %>%
  mutate(value1 = str_extract(value, 
                '^(he following object|Attaching package:|package ‘ggplot2)'), 
         value = coalesce(value1, value)) %>%
  select(-value1)

#  ID               value
#1  1 he following object
#2  2  Attaching package:
#3  3    package ‘ggplot2
#4  4   Warning messages: