我有一个testData
由许多唯一 ID 组成的数据框。我的目标是确定的ID是否包含所有可能的整数的范围内month
,yday
和week
其中min为每个ID和max的第一个值是在塔的整个范围内的最大值
换句话说,如果id
在范围内具有所有可能的值month
,那么它应该接收一个t
。例如,在month
where id
= 1 下,最小值为 2,整列的最大值为 5,因此 1 应为真,因为存在值 2、3、4 和 5。id
然而,Where = 2,只有值 1、2、4 和 5,所以 3 被跳过,因此 2 应该收到一个f
.
到目前为止,我有一个公式,它采用列的整个范围内的所有值(但不是每个的最小值id
):
library(data.table)
setDT(testData)
output<-testData[,.(month=all(unique(testData$month)%in%.SD$month),yday=all(unique(testData$yday)%in%.SD$yday),week=all(unique(testData$week)%in%.SD$week)),by=(id)]
任何想法我怎么能融入min
其中,min
为每最小值id
,并max
在范围内的最大价值?
> testData
id month yday week
1 1 2 1 1
2 3 1 2 1
3 4 1 3 1
4 2 1 4 1
5 3 3 5 2
6 4 3 6 3
7 2 2 7 1
8 3 1 8 3
9 1 2 9 2
10 5 4 10 3
11 3 2 11 1
12 4 4 12 1
13 5 4 13 2
14 1 3 14 3
15 1 4 15 1
16 1 5 16 2
17 2 4 17 3
18 2 5 18 1
19 5 5 19 1
> dput(testData)
structure(list(id = c(1L, 3L, 4L, 2L, 3L, 4L, 2L, 3L, 1L, 5L,
3L, 4L, 5L, 1L, 1L, 1L, 2L, 2L, 5L), month = c(2L, 1L, 1L, 1L,
3L, 3L, 2L, 1L, 2L, 4L, 2L, 4L, 4L, 3L, 4L, 5L, 4L, 5L, 5L),
yday = 1:19, week = c(1L, 1L, 1L, 1L, 2L, 3L, 1L, 3L, 2L,
3L, 1L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 1L)), .Names = c("id",
"month", "yday", "week"), class = "data.frame", row.names = c(NA,
-19L))
最后,输出应如下所示:
> output
id month yday week
1 1 t f t
2 2 f f f
3 3 f f t
4 4 f f f
5 5 t f t
使用dplyr
您可以分组id
,然后只需检查范围的所有元素是否都在每个组的值中。请注意,min(month)
给出分组id
变量max(testData$month)
的最小值,但给出整个列表的最大值。
library(dplyr)
tD2 <- testData %>% group_by(id) %>%
summarise(month=all(min(month):max(testData$month) %in% month),
yday=all(min(yday):max(testData$yday) %in% yday),
week=all(min(week):max(testData$week) %in% week))
tD2
# A tibble: 5 × 4
id month yday week
<int> <lgl> <lgl> <lgl>
1 1 TRUE FALSE TRUE
2 2 FALSE FALSE FALSE
3 3 FALSE FALSE TRUE
4 4 FALSE FALSE FALSE
5 5 TRUE FALSE TRUE
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句