我有一个由“0”和“1”组成的数据框,如下所示:
DATA <- data.frame("V1" = c(0,0,0,0,1,1,0,1,1,1),
"V2" = c(1,0,0,0,1,1,0,1,1,1),
"V3" = c(0,0,0,0,1,0,0,1,1,1),
"V4" = c(1,1,1,0,1,1,0,1,1,1),
"V5" = c(0,0,0,0,1,1,0,1,1,1))
我想知道在每一行中有多少次“0”后跟下一列中的“1”。如果第一列值为“1”,则也应计算在内。
我有一个循环将每一行绑定(bind)到一个向量中,然后使用 stringi::stri_count_fixed
或 stringr::str_count
计算“01”的数量:
for(n in 1:nrow(DATA)) {
# Paste row into a single character vector, with extra 0 at start in case
# the first column value is 1.
STRING <- do.call(paste0, c(0, DATA[n, 1:ncol(DATA)]))
# Count number of 0-1 transitions.
COUNT <- stringr::str_count(STRING, pattern = "01")
# Add this to the summary column.
DATA$Count[n] <- COUNT
}
但是,对于我的真实数据集(3000 - 4000 列),这两个都非常慢。有什么加快速度的想法吗?
期望的输出:
> DATA$Count
[1] 2 1 1 0 1 2 0 1 1 1
最佳答案
一个可能的解决方案,在 base R
中:
DATA$Count <-
apply(DATA, 1, \(x) x[1] + sum((x[2:length(x)] - x[1:(length(x)-1)]) > 0))
DATA
#> V1 V2 V3 V4 V5 Count
#> 1 0 1 0 1 0 2
#> 2 0 0 0 1 0 1
#> 3 0 0 0 1 0 1
#> 4 0 0 0 0 0 0
#> 5 1 1 1 1 1 1
#> 6 1 1 0 1 1 2
#> 7 0 0 0 0 0 0
#> 8 1 1 1 1 1 1
#> 9 1 1 1 1 1 1
#> 10 1 1 1 1 1 1
关于R计算连续列中模式匹配的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72434916/