r - 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
解决方案
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
推荐阅读
- postgresql - 是否可以在 PostgreSQL 函数中缓存变量?
- javascript - 如果字符串包含正则表达式中的某个单词,如何丢弃匹配项?
- python - 不使用 join() 列出
- azure-blob-storage - Azure 存储,读取 blob 层的价格?
- android - 你能推断出单个视图的约束吗?
- javascript - VSCode:如何仅在 JSDoc 定义的属性或类中自动完成?
- node.js - 我如何确保我的循环在所有功能都运行完毕的情况下完成?
- php - Laravel API Session 数据从不同的客户端返回不同的值
- jquery - jquery循环点击功能有错误的结果
- excel - 如何调用包含循环但只运行该循环的一次迭代的宏?