如何选择符合特定条件的行和上面的行?

问题描述 投票:0回答:2

这是我定义条件的方式,但我也需要上面的行。每个 ID 有很多观察结果。

data2<- data2 %>% 
  group_by (ID_number)  %>%  
  filter(time_diff_hour > 8.000 | is.na(time_diff_hour))
r select filter conditional-statements
2个回答
1
投票

您可以使用

lead
函数添加过滤条件,这将返回测试行上方的行。相反,如果您需要返回测试下方的一行,您可以使用
lag
函数。

data2<- data2 %>% 
  group_by (ID_number)  %>%  
  filter(time_diff_hour > 8.000 | is.na(time_diff_hour) | 
         lead(time_diff_hour) > 8.000 | is.na(lead(time_diff_hour)))

0
投票

这是基本 R 的解决方案:

# Generate a sample data frame
data2 <- data.frame(ID_number = rep(factor(sample(1000:9999, 10, replace=TRUE)), 4),
                 time_diff_hour = sample(c(NA, 4:12), 40, replace=TRUE))

# Find indices matching the criteria
i <- which(data2$time_diff_hour > 8 | is.na(data2$time_diff_hour)) # initial matches
i <- sort(unique(c(i, i-1))) # combine initial matches with previous rows
i <- i[i %in% seq_along(data2$time_diff_hour)] # to ensure only valid indices are used (i.e. for case where a match is generated in row #1)

data2[i, ]

我意识到这相当笨重(如果可以简化/缩短,请告诉我!) - 我们拥有 dplyr/tidyverse 的原因之一......

© www.soinside.com 2019 - 2024. All rights reserved.