我有一个包含鸟类开始迁徙日期的数据集。我想为每个人在这个数据集中添加7行,其中包含他们出发前7天的日期,并有一个填充列,其中包含另一个变量(0,1),用于确定个人是否在该日期迁移。
我一直在尝试使用dplyr complete函数,但我找不到一种方法来设置它,使最小值和最大值根据迁移日期“浮动”。
#migration dates for 10 individuals
date <- c(212, 224, 197, 210, 197, 224, 188, 212, 221, 198)
id <- c(1:10)
df <- data.frame(cbind(id, date))
#attempt to use complete function
df <- df %>%
mutate(depYN = 1) %>%
complete(date = date - seq(from = 7, to = 0),
nesting(id),
fill = list(depYN = 0))
我得到以下警告消息与此代码:
Warning message:
In date - seq(from = 7, to = 0) :
longer object length is not a multiple of shorter object length
此外,它没有产生我想要的结果,相反,depYN似乎随机分配1和0,日期范围是错误的。
前两个人的预期输出:
date id depYN
205 1 0
206 1 0
207 1 0
208 1 0
209 1 0
210 1 0
211 1 0
212 1 1
217 2 0
218 2 0
219 2 0
220 2 0
221 2 0
222 2 0
223 2 0
224 2 1
etc...
(已更新)当前代码和实际数据集
df1 <- lastDet %>%
mutate(doy = yday(depDate),
depYN = 0) %>%
select(-depDate)
df3 <- df1 %>%
group_by(mfgID) %>%
expand(doy = ((doy-7):doy)) %>%
left_join(., {df1 %>% mutate(depYN = 1)},
by = c('mfgID', 'doy')) %>%
arrange(mfgID, doy)
dput(lastDet[1:10,])
structure(list(speciesEN = c("Bank", "Bank", "Bank", "Bank", "Bank",
"Bank", "Bank", "Bank", "Bank", "Bank"), tagDeploySite =
structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 5L, 5L), .Label =
c("AU", "CB", "DE", "GA", "TR", "WE"), class = "factor"), sex =
structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L), .Label = c("F",
"M"), class = "factor"), mfgID = c("46", "47", "48", "49", "40",
"41", "42", "44", "38", "50"), depDate =
structure(c(1533032604.2326, 1534086023.11, 1531737149.7107,
1532882823.5637, 1531737145.3837, 1534093849.7991, 1530997725.9412,
1533041446.3001, 1533820579.7317, 1531824345.5634), class =
c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, -10L),
class = c("grouped_df", "tbl_df", "tbl", "data.frame"), vars =
c("speciesEN", "tagDeploySite", "sex"), drop = TRUE, indices =
list(0:3, 4:7, 8:9), group_sizes = c(4L, 4L, 2L), biggest_group_size
= 4L, labels = structure(list(speciesEN = c("Bank", "Bank", "Bank"),
tagDeploySite = structure(c(2L, 2L, 5L), .Label = c("AU", "CB",
"DE", "GA", "TR", "WE"), class = "factor"), sex = structure(c(1L,
2L, 1L), .Label = c("F", "M"), class = "factor")), row.names =
c(NA, -3L), class = "data.frame", vars = c("speciesEN",
"tagDeploySite", "sex"), drop = TRUE))
2条答案
按热度按时间oo7oh9g91#
您也可以像在问题中那样使用
complete
k5ifujac2#
我们可以在
(date-7):date)
和join
上使用原始数据集来得到depYN
。