首页 > 解决方案 > mutate & rowwise & grepl 的替代品

问题描述

我正在研究如下所示的数据框,并希望计算 A 列中某些模式(“B”和“C”)的出现。

使用 rowwise、mutate 和 grepl 的代码确实有效,但使用 rowwise 非常慢。我想知道是否有任何替代方法来获得相同的结果?

temp <- data.frame(
  A = c('A','B','C','BC')
)

temp %>% 
  dplyr::rowwise() %>%
  mutate( B = sum(grepl(pattern = 'B',A),grepl(pattern = 'C',A) ) )

结果:

# A tibble: 4 x 2
# Rowwise: 
  A     Count
  <chr> <int>
1 A         0
2 B         1
3 C         1
4 BC        2

标签: rdplyrgreplrowwise

解决方案


grepl是矢量化的,这是你sum的问题。改用+

temp %>% 
  mutate( 
    Count = grepl(pattern = 'B', A) + grepl(pattern = 'C', A)
  )
#    A Count
# 1  A     0
# 2  B     1
# 3  C     1
# 4 BC     2

与此相同的区别:

sum(1:3,  1:3)
# [1] 12

1:3 + 1:3
# [1] 2 4 6

推荐阅读