r - R:按id将两个日期列合并为一个
问题描述
我目前在数据表中的 R 中工作,并且有两个日期列(first_day 和 last_day),我需要将它们合并到一个日期列(date)中。需要这样做,以便该列具有按组(id)从最小到最大的日期。
这是我正在使用的数据:
ID first_day last_day
1 1/12/2005 1/15/2005
2 2/15/2006 2/19/2006
2 3/8/2006 3/12/2006
3 1/9/2008 1/13/2008
这是我试图让结果看起来像的内容:
ID first_day last_day Date
1 1/12/2005 1/15/2005 1/12/2005
1 1/12/2005 1/15/2005 1/15/2005
2 2/15/2006 2/19/2006 2/15/2006
2 2/15/2006 2/19/2006 2/19/2006
2 3/8/2006 3/12/2006 3/8/2006
2 3/8/2006 3/12/2006 3/12/2006
3 1/9/2008 1/13/2008 1/9/2008
3 1/9/2008 1/13/2008 1/13/2008
非常感谢任何帮助!
解决方案
out <- df[rep(1:nrow(df), each = 2),] # repeat each row
out$Date <- with(df, c(rbind(first_day, last_day))) # interlace two columns
# or out$Date <- with(out, ifelse(seq_along(first_day) %% 2, first_day, last_day))
out
# ID first_day last_day Date
# 1 1 1/12/2005 1/15/2005 1/12/2005
# 1.1 1 1/12/2005 1/15/2005 1/15/2005
# 2 2 2/15/2006 2/19/2006 2/15/2006
# 2.1 2 2/15/2006 2/19/2006 2/19/2006
# 3 2 3/8/2006 3/12/2006 3/8/2006
# 3.1 2 3/8/2006 3/12/2006 3/12/2006
# 4 3 1/9/2008 1/13/2008 1/9/2008
# 4.1 3 1/9/2008 1/13/2008 1/13/2008
或者
library(data.table)
setDT(df)
df[, .(Date = c(first_day, last_day)), by = .(ID, first_day, last_day)]
# ID first_day last_day Date
# 1: 1 1/12/2005 1/15/2005 1/12/2005
# 2: 1 1/12/2005 1/15/2005 1/15/2005
# 3: 2 2/15/2006 2/19/2006 2/15/2006
# 4: 2 2/15/2006 2/19/2006 2/19/2006
# 5: 2 3/8/2006 3/12/2006 3/8/2006
# 6: 2 3/8/2006 3/12/2006 3/12/2006
# 7: 3 1/9/2008 1/13/2008 1/9/2008
# 8: 3 1/9/2008 1/13/2008 1/13/2008
推荐阅读
- ios - 使用 xamarin 应用程序覆盖现有的 ios 本机应用程序
- ios - AVAudioFile 将原始 PCM 编码为 AAC 时文件非常大
- list - Flutter / Dart如何组合地图列表中的值
- python - 将子字符串循环到新列
- android - 添加依赖项时出现重复的类错误 | 如何删除特定类
- node.js - NodeJS Asyn/Await 用于使用 nodecloud-config-client 构建配置
- javascript - 无法读取未定义的属性(尝试在初始化之前访问属性)
- typescript - 抽象类中的可选只读属性或 getter
- javascript - HighCharts 错误栏显示不正确
- sql - 从 YMD HMS UTC sql bigquery 中解析出 YMD