R:多个时间戳列合并为时间戳系列
数据帧包含多个时间戳列R:多个时间戳列合并为时间戳系列,r,timestamp,posix,R,Timestamp,Posix,数据帧包含多个时间戳列 # Create simple example df <- cbind.data.frame(A=c("A","B","C") ,B=c(1,2,3) ,Timestamp_1=c(as.POSIXct(NA),as.POSIXct("2018-05-04 00:19:41"),as.POSIXct("2018-07-31 22:09:10")) ,Timestamp_2=c(as.POSIXct("2018-05-04
# Create simple example
df <- cbind.data.frame(A=c("A","B","C")
,B=c(1,2,3)
,Timestamp_1=c(as.POSIXct(NA),as.POSIXct("2018-05-04 00:19:41"),as.POSIXct("2018-07-31 22:09:10"))
,Timestamp_2=c(as.POSIXct("2018-05-04 00:18:45"),as.POSIXct("2018-05-05 00:18:43"),as.POSIXct("2018-06-05 00:00:01"))
,Timestamp_3=c(as.POSIXct("2018-05-04 00:19:13"),as.POSIXct("2018-05-05 00:17:00"),as.POSIXct("2018-05-06 00:18:41"))
,C=c("Dog","Cat","Mouse")
)
df
A B Timestamp_1 Timestamp_2 Timestamp_3 C
1 A 1 <NA> 2018-05-04 00:18:45 2018-05-04 00:19:13 Dog
2 B 2 2018-05-04 00:19:41 2018-05-05 00:18:43 2018-05-05 00:17:00 Cat
3 C 3 2018-07-31 22:09:10 2018-06-05 00:00:01 2018-05-06 00:18:41 Mouse
合并时间戳列的结果需要如下所示
df_Result
A B Timestamp_ALL C
1 A 1 <NA> Dog
2 A 1 2018-05-04 00:18:45 Dog
3 A 1 2018-05-04 00:19:13 Dog
4 B 2 2018-05-04 00:19:41 Cat
5 B 2 2018-05-05 00:17:00 Cat
6 B 2 2018-05-05 00:18:43 Cat
7 C 3 2018-05-06 00:18:41 Mouse
8 C 3 2018-06-05 00:00:01 Mouse
9 C 3 2018-07-31 22:09:10 Mouse
如何以R-优雅且高效的方式实现这一点?
非常感谢你的建议和想法 下面是一个使用tidyr::gather的tidyverse解决方案
说明:gather将data.frame从宽转换为长,其余的只是使用select选择相关列,然后使用arrange按A排序条目,然后按B排序条目 下面是一个使用tidyr::gather的tidyverse解决方案
说明:gather将data.frame从宽转换为长,其余的只是使用select选择相关列,然后使用arrange按A排序条目,然后按B排序条目 效果很好。非常好-非常感谢!非常欢迎@user2006697!效果很好。非常好-非常感谢!非常欢迎@user2006697!
library(tidyverse)
df %>%
gather(key, Timestamp_ALL, -A, -B, -C) %>%
select(A, B, Timestamp_ALL, C, -key) %>%
arrange(A, B)
# A B Timestamp_ALL C
#1 A 1 <NA> Dog
#2 A 1 2018-05-04 00:18:45 Dog
#3 A 1 2018-05-04 00:19:13 Dog
#4 B 2 2018-05-04 00:19:41 Cat
#5 B 2 2018-05-05 00:18:43 Cat
#6 B 2 2018-05-05 00:17:00 Cat
#7 C 3 2018-07-31 22:09:10 Mouse
#8 C 3 2018-06-05 00:00:01 Mouse
#9 C 3 2018-05-06 00:18:41 Mouse