我有一个包含多列和自定义函数的大数据表。数据表看起来像这样,有八种不同的bird_ID
类型:
GPS_ID bird_ID device_ID devicetype timestamp date
1: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02
2: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02
3: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02
4: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02
5: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02
6: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02
自定义函数计算两行的timestamp
之间的时间差,并在名为Position.Burst.ID
的新列中指定一个数字。如果diff
超过5秒,则编号序列前进,否则保留先前分配的编号。
pbid <- function(data_table) {
newbout <- which(c(TRUE, diff(as.POSIXct(data_table$timestamp, tz = "UTC")) >= 5) == T)
boutind <- rep(seq_along(newbout), diff(c(newbout, (nrow(data_table) + 1))))
data_table$Position.Burst.ID <- boutind
}
此功能与一个bird_ID
配合使用非常好。
GPS_ID bird_ID device_ID devicetype timestamp date Position.Burst.ID
1: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02 1
2: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02 1
3: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02 1
4: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02 1
5: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02 1
6: NA 350E 202927 ornitela 2022-05-02 00:03:59 2022-05-02 1
我想要group_by(bird_ID)
,所以它将从顶部开始为每个bird_ID
计数
data_table %>%
group_by(bird_ID) %>%
mutate(Position.Burst.ID = pbid(data_table))
这肯定没有奏效,因为:
`Position.Burst.ID` must be size 419335 or 1, not 4592293.
关于如何处理这个问题,有什么想法吗?
我已经尝试创建一个循环并将函数放入其中,但这也是一条死胡同。我真的想避免使用for
循环来处理这么多数据。
以下是我的操作方法:
data_table %>%
group_by(bird_ID) %>%
mutate(Position.Burst.ID = cumsum(timestamp - lag(timestamp, default = timestamp[1]) >= 5) + 1)