这是示例数据。
created_date start_date
2014-12-11 2014-12-10
2014-12-11 2014-12-11
2014-12-12 2014-12-13
2014-12-13 NULL
2014-12-13 2014-12-13
2014-12-13 2014-12-13
2014-12-23 NULL
2014-12-23 NULL
我想根据created_date来计算每天检查了多少start_date。start_date的值并不重要,只有检查的start_date"数量"才有意义。
在这种情况下,for循环的结果应该是这样的
created_date count
2014-12-11 2
2014-12-12 1
2014-12-13 2
2014-12-23 0
我不能简单地使用table(),因为:
表(created_date)将计算created_date,而不是start_date。
>table(created_date)
created_date count
2014-12-11 2
2014-12-12 1
2014-12-13 3
2014-12-23 2
表(start_date)也不起作用,因为它不计算"NULL"的创建日期,更重要的是,start_date本身的值是没有意义的。
>table(start_date)
created_date count
2014-12-10 1
2014-12-11 1
2014-12-13 3
NULL 3
我想应该使用for循环,但不知道如何编码。提前感谢!
简短版本:分别对完整数据和空行使用table
,第一行减去第二行。
长版本:
假设您的数据在x
中(而NULL
实际上是NA
,请参阅Gist了解详细信息):
对条目进行计数,并将其放入data_frame
s中以方便使用:
library(dplyr)
all_counts = as_data_frame(table(x$created_date))
na_counts = as_data_frame(table(x[is.na(x$start_date), ]$created_date))
从full_counts
中减去na_counts
。为此,我们首先需要连接这两个表。加入我们将推出NA
将替换为0
s:
full_join(all_counts, na_counts, by = 'Var1') %>%
mutate(n.y = ifelse(is.na(n.y), 0, n.y)) %>%
mutate(count = n.x - n.y) %>% # And finally, subtract the counts.
select(created_date = Var1, count)
结果:
| created_date | count |
|:---------------|--------:|
| 2014-12-11 | 2 |
| 2014-12-12 | 1 |
| 2014-12-13 | 2 |
| 2014-12-23 | 0 |