【问题标题】:How to write multiple transformation of the same column in one function?如何在一个函数中编写同一列的多个转换?
【发布时间】:2020-11-10 21:05:32
【问题描述】:

我有一个数据框:

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。我的实际数据要大得多(如数百万行)。这只是一个子集示例。那么,我怎样才能将这三次结合使用这个功能一次呢?我想使用相同的函数和库(没有根本的变化)

【问题讨论】:

    标签: r dataframe stringr


    【解决方案1】:

    如果我正确理解了这个问题,您应该会发现使用管道运算符 | 将代码中的 str_replace 替换为 str_replace_all 很有用,以避免需要多次调用 str_replace不同的行。

    例如:

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

    【讨论】:

    • 谢谢,用 str_starts() 函数可以做到吗?
    • 根据文档,是的,看起来这基本上与您在此处尝试执行的正则表达式相同。我试图为您提供一个超出此特定用例的通用模式。
    • 你能用 str_starts() 展示它的样子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多