问题描述
我有一个数据框:
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:)','(^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_replace
,然后使用str_extract
和现有值来代替使用coalesce
和使用反向引用捕获字符串。
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: