R 查找最接近行特定日期的日期
我有以下数据帧: 第1列包含识别号respnr 第二列包含每个标识号的参考日期 第3列到第16列包含日期datesc1:datesc14 我希望输入第17列,其中第3:16列中的日期打印出来,最接近第2列中的参考日期。 我已经尝试了apply和which.min以及neardate的组合,不过我还是搞不懂R 查找最接近行特定日期的日期,r,date,R,Date,我有以下数据帧: 第1列包含识别号respnr 第二列包含每个标识号的参考日期 第3列到第16列包含日期datesc1:datesc14 我希望输入第17列,其中第3:16列中的日期打印出来,最接近第2列中的参考日期。 我已经尝试了apply和which.min以及neardate的组合,不过我还是搞不懂 如果能朝着正确的方向努力,我们将不胜感激 这个简单的例子将帮助您: # example data df = data.frame(id = c("A","B"),
如果能朝着正确的方向努力,我们将不胜感激 这个简单的例子将帮助您:
# example data
df = data.frame(id = c("A","B"),
date_ref = c("2013-01-26", "2013-01-08"),
date1 = c("2013-01-23", "2013-01-01"),
date2 = c("2013-01-20", "2013-01-07"),
stringsAsFactors = F)
df
# id date_ref date1 date2
# 1 A 2013-01-26 2013-01-23 2013-01-20
# 2 B 2013-01-08 2013-01-01 2013-01-07
library(dplyr)
library(lubridate)
library(tidyr)
# update date column to datetime variables
# (if needed)
df = df %>% mutate_at(vars(matches("date")), ymd)
df %>%
gather(type,date_new,-id,-date_ref) %>% # reshape dataset
group_by(id) %>% # for each id
filter(abs(difftime(date_ref, date_new)) == min(abs(difftime(date_ref, date_new)))) %>% # keep row with minimum distance between dates
ungroup() %>% # forget the grouping
select(-type) %>% # remove that variable
inner_join(df, by=c("id","date_ref")) # join back original dataset
# # A tibble: 2 x 5
# id date_ref date_new date1 date2
# <chr> <date> <date> <date> <date>
# 1 A 2013-01-26 2013-01-23 2013-01-23 2013-01-20
# 2 B 2013-01-08 2013-01-07 2013-01-01 2013-01-07
不确定您是否可以在基线日期之前/之后有相同距离的多个日期相同日期相同天数的多次,以及您希望如何处理这些日期。欢迎使用StackOverflow!请阅读相关信息以及如何给出建议。这将使其他人更容易帮助你。另外:永远不要用图片来显示你的数据。另请参见我之前评论中的链接。