如何计算数据帧中 TRUE 语句的数量,条件是前一个元素在 R 中也是 TRUE?

How to count the number of of TRUE statements in a dataframe, conditioned that the previous element is also TRUE in R?

我有以下虚拟数据:

data <- data.frame(c("FALSE","FALSE","TRUE","TRUE","TRUE","FALSE","FALSE","TRUE","FALSE"))

我想从这些数据中实现的是统计以下内容:

  1. n_00:假设前一个元素为“FALSE”,出现“FALSE”的次数
  2. n_01:假设前一个元素为“FALSE”,出现“TRUE”的次数
  3. n_10:假设前一个元素为“TRUE”,出现“FALSE”的次数
  4. n_11:假设前一个元素为“FALSE”,出现“TRUE”的次数

因此,虚拟数据应该给出的结果数字是:

  1. n_00= 2
  2. n_01= 2
  3. n_10= 2
  4. n_11=2

如果已经看到并尝试采用已用于涉及运行或计算连续参数但没有成功的类似问题的方法。

本质上,我想做的是根据前一个元素计算满足条件的元素数量。

如果有人知道某个页面,可以提出一个函数或循环,那将不胜感激,因为我想用大量数据来做这件事。

如何在向量上编写一个简单的循环来计算对的类型?

x <- c(FALSE,FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,TRUE,FALSE)

count_chunks <- function(x) {
  out <- NULL
  for (i in 2:length(x)) {
    out <- c(out, paste(x[i-1], x[i]))
  }
  table(out)
}

count_chunks(x)
#> out
#> FALSE FALSE  FALSE TRUE  TRUE FALSE   TRUE TRUE 
#>           2           2           2           2

您可以只使用 table 将值与滞后值进行比较:

table(previous = data[[1]][-1], current = data[[1]][-nrow(data)])
#>         current
#> previous FALSE TRUE
#>    FALSE     2    2
#>    TRUE      2    2

或者如果你想变漂亮:

as.data.frame(table(previous = data[[1]][-1], current = data[[1]][-nrow(data)]))
#>   previous current value
#> 1    FALSE   FALSE     2
#> 2     TRUE   FALSE     2
#> 3    FALSE    TRUE     2
#> 4     TRUE    TRUE     2

根据数据的大小,循环方法可能会变慢。这是一个 dplyr 方法。可能不如使用 table().

data <- data.frame( var = c("FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "FALSE", "FALSE", "TRUE", "FALSE"))
data$var <- as.logical(data$var)
data %>% 
   mutate(lag = lag(var)) %>%
   group_by(var, lag) %>%
   filter(complete.cases(lag)) %>%
   summarise(count = n()) %>%
   mutate(label = paste("n_", as.numeric(var), as.numeric(lag), sep ="")) %>%
   select(label, count)