我对识别从0到0.5或1的个体感兴趣。下面是示例数据:
id x
1 0
1 1
1 1
2 0
2 .5
2 .5
3 0
3 0
我想要一个新的df,它表示每个人是否从0移动到0.5或1。像这样;
id endorsed
1 TRUE
2 TRUE
3 FALSE
我尝试使用ifelse,但我就是不能得到正确的代码。有人有什么建议吗?
按'id'进行分组的选项,检查'x'中的any
值为0,下一个值为0.5或1(使用lead
)(假设精度正确)
library(dplyr)
df1 %>%
group_by(id) %>%
summarise(endorsed = any(x == 0 & lead(x) %in% c( 0.5, 1)))
与产出
# A tibble: 3 x 2
# id endorsed
#* <int> <lgl>
#1 1 TRUE
#2 2 TRUE
#3 3 FALSE
数据df1 <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L), x = c(0,
1, 1, 0, 0.5, 0.5, 0, 0)), class = "data.frame", row.names = c(NA,
-8L))
由于它们总是从0开始,您可以分组并询问它们是否达到0.5或1:
df1 %>% group_by(id) %>% summarize(endorsed = any(x %in% c(0.5, 1)))
使用aggregate
的base R选项
aggregate(
cbind(endorsed = x) ~ id,
df,
function(v) head(v, 1) == 0 & tail(cummax(v), 1) %in% c(.5, 1)
)
为
id endorsed
1 1 TRUE
2 2 TRUE
3 3 FALSE