Blu*_*ist 0 datetime r time-series dplyr
我有与此处发布的相同的问题,但问题仍然没有答案,我也遇到了同样的问题.
我在这里附上了我的数据样本.
我使用的R版本是3.4.2,dplyr的版本是0.7.4.
为了让每个人都加快速度......导入数据后,我会进行以下编辑:
#specify which species are predators (pp = 1) and prey (pp = 0)
d1 = d1 %>%
group_by(sps) %>% #grouped by species
mutate(pp=ifelse(sps %in% c("MUXX", "MUVI","MEME"), 1,0)) #mutate to specify predators as 1 and prey as 0
d1$datetime=strftime(paste(d1$date,d1$time),'%Y-%m-%d %H:%M',usetz=FALSE) #converting the date/time into a new format
head(d1) #visualize the first few lines of the data
d2 = d1 %>% filter(km %in% c("80")) #restricting the observations to just one location (km 80)
Run Code Online (Sandbox Code Playgroud)
现在问题出现的地方(NAs):
d2 = d2 %>% mutate(prev = dplyr::lag(pp))
#when I look at the output I see the lag function isn't working (shown below)
> d2
# A tibble: 209 x 10
# Groups: sps [10]
ID date km culv.id type sps time pp datetime prev
<int> <fctr> <dbl> <fctr> <fctr> <fctr> <fctr> <dbl> <chr> <dbl>
1 1 2012-06-19 80 A DCC MICRO 2:19 0 2012-06-19 02:19 NA
2 2 2012-06-21 80 A DCC MUXX 23:23 1 2012-06-21 23:23 NA
3 3 2012-07-15 80 A DCC MAMO 11:38 0 2012-07-15 11:38 NA
4 4 2012-07-20 80 A DCC MICRO 22:19 0 2012-07-20 22:19 0
5 5 2012-07-29 80 A DCC MICRO 23:03 0 2012-07-29 23:03 0
6 8 2012-08-07 80 A DCC PRLO 2:04 0 2012-08-07 02:04 NA
7 9 2012-08-08 80 A DCC MICRO 23:56 0 2012-08-08 23:56 0
8 10 2012-08-09 80 A DCC PRLO 23:06 0 2012-08-09 23:06 0
9 11 2012-08-13 80 A DCC MICRO 0:04 0 2012-08-13 00:04 0
10 12 2012-08-13 80 A DCC MICRO 0:46 0 2012-08-13 00:46 0
Run Code Online (Sandbox Code Playgroud)
任何人都有任何建议为什么滞后功能不起作用?
在您之前指定的某个操作中group_by(sps),该组将保持与您的数据框连接,直到您ungroup().某些行级操作不受组影响,但聚合函数和基于多行中的值进行求值的函数将会影响.
d2 <- d2 %>% ungroup() %>% mutate(prev = dplyr::lag(pp))
Run Code Online (Sandbox Code Playgroud)
另外,关于我注意到的事情:
# Groups: sps [10] sps值的第一个实例是NA,但每个值的第二个实例正确为0但是,作为最终编辑,第一个值lag()将始终为NA,因为没有先前的值.这也是如此group_by(sps),但这意味着你将拥有10个NA值,每个因子级别的第一个实例.如果您想要组内的滞后值,那么您不应该ungroup()和函数正常工作来创建这些NA.您可以将这些NA替换为0,或者在适当的情况下替换其他值.