简体   繁体   English

越来越多地统计满足某个条件的次数(R)

[英]Increasingly count the number of times that a certain condition is met (R)

I would like to know how to increasingly count the number of times that a column in my data.frame satisfies a condition.我想知道如何越来越多地计算 data.frame 中的列满足条件的次数。 Let's consider a data.frame such as:让我们考虑一个 data.frame,例如:

x hour count
1    0    NA
2    1    NA
3    2    NA
4    3    NA
5    0    NA
6    1    NA
...

I would like to have this output:我想要这个输出:

x hour count
1    0     1
2    1    NA
3    2    NA
4    3    NA
5    0     2
6    1    NA
...

With the count column increasing by 1 everytime the condition hour==0 is met.每次满足条件hour==0count列都会增加 1。 Is there a smart and efficient way to perform this?有没有一种聪明而有效的方法来执行此操作? Thanks谢谢

You can use seq_along on the rows where hour == 0 .您可以在hour == 0的行上使用seq_along

i <- x$hour == 0
x$count[i] <- seq_along(i)
x
#  x hour count
#1 1    0     1
#2 2    1    NA
#3 3    2    NA
#4 4    3    NA
#5 5    0     2
#6 6    1    NA

Data:数据:

x <- structure(list(x = 1:6, hour = c(0L, 1L, 2L, 3L, 0L, 1L), count = c(NA, 
NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-6L))

You can use cumsum to count incremental number of 0 occurrences and replace counts where hour values is not 0 to NA .您可以使用cumsum来计算 0 出现的增量数量,并将hour值不为 0 的counts替换为NA

library(dplyr)
df %>%
  mutate(count = cumsum(hour == 0), 
         count = replace(count, hour != 0 , NA))

#  x hour count
#1 1    0     1
#2 2    1    NA
#3 3    2    NA
#4 4    3    NA
#5 5    0     2
#6 6    1    NA

data数据

df <- structure(list(x = 1:6, hour = c(0L, 1L, 2L, 3L, 0L, 1L)), 
class = "data.frame", row.names = c(NA, -6L))

Using data.table使用数据data.table

library(data.table)
setDT(df)[hour == 0, count := seq_len(.N)]
df
#   x hour count
#1: 1    0     1
#2: 2    1    NA
#3: 3    2    NA
#4: 4    3    NA
#5: 5    0     2
#6: 6    1    NA

data数据

df <- structure(list(x = 1:6, hour = c(0L, 1L, 2L, 3L, 0L, 1L)), 
class = "data.frame", row.names = c(NA, -6L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM