【发布时间】:2019-08-14 20:29:22
【问题描述】:
我有两个数据框(df1 和 df2);它们每个都有一个 ID 列,并按 ID 号组织,每个数据帧的每个 ID 有很多行。 df1 有一个“unique_posix”列,df2 有一个“date.time.start”和“date.time.end”列,还有一个“depth”和“shape”列。 对于每个 ID,我想从 df1 中获取我的“unique_posix”列并转到 df2 并找到它介于两者之间或之上的“date.time.start”和“date.time.end”。当我找到它对应的行时,我想从 df2 中提取“深度”和“形状”,并将其复制到 df1 中该唯一日期/时间的新列。
我已经尝试使用 if/else 作为 for 循环来执行此操作,并且我已尝试在 dplyr 中执行此操作。
df1<-data.frame(ID=c('SW12','SW12','SW12','SW12','SW12','SW13','SW13','SW13','SW13','SW13'), unique_posix=c('5/3/10 16:47','5/3/10 16:53','5/3/10 17:00', '5/3/10 18:00','5/3/10/ 18:12','8/15/10 17:13','8/15/10 17:18','8/15/10 17:37','8/15/10 18:00','8/15/10 18:52'))
df2<- data.frame(ID=c('SW12','SW12','SW12','SW12','SW12','SW13','SW13','SW13','SW13','SW13'), Date.Time.Start=c('5/3/10 15:57','5/3/10 16:18', '5/3/10 16:55','5/3/10 17:36','5/3/10 18:17','8/15/10 16:55','8/15/10 17:28','8/15/10 17:54', '8/15/10 18:55','8/15/10 19:20'), Date.Time.End=c('5/3/10 16:09','5/3/10 16:44','5/3/10 17:28', '5/3/10 18:08', '5/3/10 18:49', '8/15/10 17:22', '8/15/10 17:52','8/15/10 18:06','8/15/10 19:15','8/15/10 19:40'), Shape=c('U','U','V','Square','U','U','U','Square','V','U'), Depth=c(1,2,3,4,5,6,7,8,9,10))
我希望 df1 最终看起来像:
df1b<-data.frame(ID=c('SW12','SW12','SW12','SW12','SW12','SW13','SW13','SW13','SW13','SW13'), unique_posix=c('5/3/10 16:47','5/3/10 16:53','5/3/10 17:00', '5/3/10 18:00','5/3/10/ 18:12','8/15/10 17:13','8/15/10 17:18','8/15/10 17:37','8/15/10 18:00','8/15/10 18:52'), Dive.Shape=c(NA,NA,'V','Square',NA,'U','U','U','Square', NA),Dive.Depth=c(NA,NA,3,4,NA,6,6,7,8,NA))
我已将日期/时间转换为 POSIXct/lt:
library(dplyr)
df1 <- df1 %>%
mutate(
ID = factor(ID),
unique_posix = mdy_hm(unique_posix)
)
class(df1$unique_posix)
df2 <- df2 %>%
mutate(
ID = factor(ID),
Date.Time.Start = mdy_hm(Date.Time.Start),
Date.Time.End = mdy_hm(Date.Time.End)
)
class(df2$Date.Time.Start)
作为一个for循环我试过了:
df1b<-df1
for (i in 1:nrow(df1)) {
if (df1$unique_posix %within% interval(df2$Date.Time.Start, df2$Date.Time.End)) {
df1b$Dive.Shape<-df2$Shape
df1b$Dive.Depth<-df2$Depth
}
else {
df1b$Dive.Shape<-NA
df2b$Dive.Depth<-NA
}
}
在 dplyr 我正在尝试这样的事情:
df1b<-inner_join(df1, df2, by="DeployID")
df1b %>% rowwise() %>%
mutate(Dive.Shape=ifelse(between(unique_posix, Date.Time.Start, Date.Time.End),Shape,NA )) %>%
mutate(Dive.Depth=ifelse(between(unique_posix, Date.Time.Start, Date.Time.End),Depth,NA ))
arrange(DeployID,desc(unique_posix)) %>%
distinct(unique_posix)
这些似乎都不起作用,但我觉得我很接近?
我希望我的 df1b 有两个额外的 Dive.Shape 和 Dive.Depth 列,如果 unique_posix 日期/时间不在 Date.Time 之内或之上,则它将包含一个“NA”。 df2 框架中的 Start 和 Date.Time.End 范围[对于每个 ID]。如果 df1 的 unique_posix 介于 df2 的 Date.Time.Start 或 Date.Time.End 列之间或之上,则这些列将包含来自 df2 的 Shape 和 df2 的 Depth 列的值。
感谢您为我提供的任何帮助!
【问题讨论】:
标签: r function datetime dplyr between