[英]dplyr function returning false NAs
我有與此處發布的問題相同的問題,但問題仍未得到解答,我也有同樣的問題。
我在這里附上了我的數據樣本。
我正在使用的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)
現在針對出現問題的地方(NA):
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
有人對滯后功能為什么不起作用有什么建議嗎?
在先前的操作之一中,您指定了group_by(sps)
,該組將保持與數據框的連接,直到您ungroup()
group ungroup()
為止。 某些行級別的操作不受組的影響,但會聚合函數,並且基於多於一行的值求值的函數將受到影響。
d2 <- d2 %>% ungroup() %>% mutate(prev = dplyr::lag(pp))
另外,關於我注意到的是:
# Groups: sps [10]
看到了# Groups: sps [10]
sps
值的第一個實例為NA,但每個第二個實例正確為0 但是,作為最終編輯,因為沒有先前的值,所以lag()
的第一個值將始終為NA。 group_by(sps)
也是這樣,但是這意味着您將有10個NA值,每個因子級別的第一個實例都有一個。 如果要在組中使用滯后值,則不應ungroup()
並且函數可以正常創建這些NA。 您可以將這些NA替換為0,也可以使用其他值替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.