根据另一个数据帧中的行索引将 POSIXt 日期拉入另一个数据帧作为新列 - 可重现
我在下面有数据框“ DF1”,其中包含与数据框架“ DF”行相关的行索引。
我想使用DF1中的行索引在DataFrame DF中引入相应的行。即,第一行DF1是4和6,我想在DF1中创建两个新列,它们是开始时间(DF第4行)和结束时间(DF第6行的时间戳)。
实际的数据范围要长得多,因此一般代码可以有所帮助
df1 <- structure(list(co2_start = c(4, 6, 9, 12), co2_end = c(6, 9,
12, 15)), class = "data.frame", row.names = c(NA, -4L))
df <- structure(list(date = structure(c(1623481200, 1623481500, 1623481800,
1623482100, 1623482400, 1623482700, 1623483000, 1623483300, 1623483600,
1623483900, 1623484200, 1623484500, 1623484800, 1623485100, 1623485400
), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA,
-15L), class = "data.frame")
,因此我希望DF1看起来像下面
4 6 2021-06-12 00:15:00 2021-06-12 00:25:00
6 9 2021-06-12 00:25:00 2021-06-12 00:40:00
9 12 2021-06-12 00:40:00 2021-06-12 00:55:00
12 15 2021-06-12 00:55:00 2021-06-12 01:10:00
I have the dataframe "df1" below which contains row indices that relate to the rows of data frame "df".
I want to use the row indices in df1 to bring in the corresponding row in the dataframe df. i.e., the first row df1 is 4 and 6 and I want to create two new columns in df1 that are start time (timestamp on row 4 of df) and end time (timestamp on row 6 of df).
Actual dataframes are much longer so general code to do this would help
df1 <- structure(list(co2_start = c(4, 6, 9, 12), co2_end = c(6, 9,
12, 15)), class = "data.frame", row.names = c(NA, -4L))
df <- structure(list(date = structure(c(1623481200, 1623481500, 1623481800,
1623482100, 1623482400, 1623482700, 1623483000, 1623483300, 1623483600,
1623483900, 1623484200, 1623484500, 1623484800, 1623485100, 1623485400
), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA,
-15L), class = "data.frame")
So I would like df1 to look like below
4 6 2021-06-12 00:15:00 2021-06-12 00:25:00
6 9 2021-06-12 00:25:00 2021-06-12 00:40:00
9 12 2021-06-12 00:40:00 2021-06-12 00:55:00
12 15 2021-06-12 00:55:00 2021-06-12 01:10:00
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的
df1
已经是行索引,因此您只需使用dplyr :: mutate()
创建列并在开始/结束列中的值子集。由
Since your
df1
are already row indices, you can just usedplyr::mutate()
to create your columns and subset with the values in start/end columns.Created on 2022-03-29 by the reprex package (v2.0.1)