【问题标题】:R mutate & gsub where pattern is based on a columnR mutate & gsub 其中模式基于列
【发布时间】:2020-11-24 10:29:58
【问题描述】:

我正在尝试使用mutate()gsub()var_1 中删除pattern

由于gsub() 只需要一个字符串,我必须在mutate() 之前使用rowwise()。否则它将只使用pattern 列中的第一条记录。

我想知道是否有任何其他方法可以在不使用rowwise() 的情况下达到相同的结果,因为它会大大减慢进程。

test <- data.frame(
  var_1 = c('1AB', '2AB', '3C')
  ,pattern = c('AB','A','C')
)

test %>%
  dplyr::rowwise() %>%
  dplyr::mutate( result = sub(pattern, '', var_1)
          )

期望的结果:

# A tibble: 3 x 4
# Rowwise: 
  var_1 var_2 pattern result
  <chr> <lgl> <chr>   <chr> 
1 1AB   FALSE AB      1     
2 2AB   TRUE  A       2B    
3 3C    FALSE C       3 

【问题讨论】:

    标签: r gsub dplyr rowwise


    【解决方案1】:

    您可以使用矢量化的stringr 选项。

    使用str_remove

    library(dplyr)
    library(stringr)
    
    test %>% mutate(result = str_remove(var_1, pattern))
    
    #  var_1 pattern result
    #1   1AB      AB      1
    #2   2AB       A     2B
    #3    3C       C      3
    

    这与使用str_replace 替换为"" 相同。

    test %>%  mutate(result = str_replace(var_1, pattern, ''))
    

    【讨论】:

    • 谢谢罗纳克!我试图比较 mutate + str_replace 和 with + str_replace 似乎 mutate + str_replace 要慢得多。你知道为什么会这样吗(请参阅我下一条评论中的代码)?
    • microbenchmark::microbenchmark(test %>% mutate(temp = stringr::str_remove(string = var_1,pattern = pattern)),with(test, stringr::str_remove(string = var_1,pattern = 模式 ) ) , 次 = 10L )
    • 我实际上并不知道mutate 是否会增加额外的开销。您正在对多少行数据进行测试?
    • 我使用的数据帧与上面定义的相同,所以 3 行,mutate 方法至少比with 方法花费的时间长 10 倍
    • 3 行无法获得任何有意义的结果。将您的数据扩展到至少 10k 行,然后进行测试。
    【解决方案2】:

    我们可以使用map2

    library(dplyr)
    library(purrr)
    test %>% 
          mutate(result = map2_chr(var_1, pattern, ~ sub(.y, '', .x)))
    

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 2021-10-12
      • 1970-01-01
      相关资源
      最近更新 更多