【问题标题】:Finding the first row after which x rows meet some criterium in R查找第一行,之后 x 行满足 R 中的某些标准
【发布时间】:2021-11-20 22:52:51
【问题描述】:

一个数据争论的问题:

我有一个每小时动物跟踪点的数据框,其中包含 id、时间以及动物是在陆地上还是在水中(0 = 水;1 = 陆地)的列。它看起来像这样:

set.seed(13)
n <- 100
dat <- data.frame(id = rep(1:5, each = 10),
                  datetime=seq(as.POSIXct("2020-12-26 00:00:00"), as.POSIXct("2020-12-30 3:00:00"), by = "hour"),
                  land = sample(0:1, n, replace = TRUE))

我需要做的是标记第一行,之后动物至少连续 3 天使用土地一次。我试着做这样的事情:


dat$ymd <- ymd(dat$datetime[1]) # make column for year-month-day

# add land points within each id group

land.pts <- dat %>% 
  group_by(id, ymd) %>%
  arrange(id, datetime) %>%
  drop_na(land) %>%
  mutate(all.land = cumsum(land))

#flag days that have any land points

flag <- land.pts %>%
  group_by(id, ymd) %>%
  arrange(id, datetime) %>%
  slice(n()) %>%
  mutate(flag = if_else(all.land == 0,0,1))

# Combine flagged dataframe with full dataframe

comb <- left_join(land.pts, flag)
comb[is.na(comb)] <- 1

然后我尝试了这个:

x = comb %>% 
  group_by(id) %>% 
  arrange(id, datetime) %>% 
  mutate(time.land=ifelse(land==0 | is.na(lag(land)) | lag(land)==0 | flag==0, 
                          0,
                          difftime(datetime, lag(datetime), units="days"))) 

但是我仍然无法完全确定要做什么才能做到这一点,以便我可以弄清楚动物连续三天至少在陆地上一次的时间,然后在陆地上标记第一个点。非常感谢您提供的任何帮助!

【问题讨论】:

标签: r dplyr tidy


【解决方案1】:

从时间戳创建一个日期列。汇总数据并为每个iddate 保留1 行,这表明animal 一整天是否在陆地上。

如果接下来的 3 天动物都在陆地上,请使用 zoorollapply 函数将第一天标记为 TRUE

library(dplyr)
library(zoo)

dat <- dat %>% mutate(date = as.Date(datetime))

dat %>%
  group_by(id, date) %>%
  summarise(on_land = any(land == 1)) %>%
  mutate(consec_three = rollapply(on_land, 3,all, align = 'left', fill = NA)) %>%
  ungroup %>%
  #If you want all the rows of the data
  left_join(dat, by = c('id', 'date'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多