将 time-point 列变成间隔
Turn a time-point column into intervals
我有一个 tibble 存储 time-point 数据:
data.frame(Time = c(0, 1, 2, 3, 4), readings = c(123, 234, 145, 234, 121))
我想将它变成如下所示的 table:
From
To
Initial
End
0
1
123
234
1
2
234
145
2
3
145
234
3
4
234
121
...
...
...
...
我更喜欢用R/tidyverse来完成,但是如果python可以用更简单的方式来完成,我也可以采用一些python代码。谢谢!
这个有用吗:
library(dplyr)
df %>% mutate(To = lead(Time), End = lead(readings)) %>%
select('From' = Time, To, 'Initial' = readings, End)
From To Initial End
1 0 1 123 234
2 1 2 234 145
3 2 3 145 234
4 3 4 234 121
我们可以在 base R
中删除数据集的最后一行和第一行并重命名列
setNames(cbind(df1[-nrow(df1), ], df1[-1, ]),
c("From", "Initial", "To", "End"))[c(1, 3, 2, 4)]
From To Initial End
1 0 1 123 234
2 1 2 234 145
3 2 3 145 234
4 3 4 234 121
这是另一种 dplyr
方法:使用 across
df %>%
mutate(across(everything(), lead, .names="end_{col}")) %>%
select(From=Time, To=end_Time, Initial=readings, End=end_readings)
From To Initial End
1 0 1 123 234
2 1 2 234 145
3 2 3 145 234
4 3 4 234 121
5 4 NA 121 NA
我有一个 tibble 存储 time-point 数据:
data.frame(Time = c(0, 1, 2, 3, 4), readings = c(123, 234, 145, 234, 121))
我想将它变成如下所示的 table:
From | To | Initial | End |
---|---|---|---|
0 | 1 | 123 | 234 |
1 | 2 | 234 | 145 |
2 | 3 | 145 | 234 |
3 | 4 | 234 | 121 |
... | ... | ... | ... |
我更喜欢用R/tidyverse来完成,但是如果python可以用更简单的方式来完成,我也可以采用一些python代码。谢谢!
这个有用吗:
library(dplyr)
df %>% mutate(To = lead(Time), End = lead(readings)) %>%
select('From' = Time, To, 'Initial' = readings, End)
From To Initial End
1 0 1 123 234
2 1 2 234 145
3 2 3 145 234
4 3 4 234 121
我们可以在 base R
中删除数据集的最后一行和第一行并重命名列
setNames(cbind(df1[-nrow(df1), ], df1[-1, ]),
c("From", "Initial", "To", "End"))[c(1, 3, 2, 4)]
From To Initial End
1 0 1 123 234
2 1 2 234 145
3 2 3 145 234
4 3 4 234 121
这是另一种 dplyr
方法:使用 across
df %>%
mutate(across(everything(), lead, .names="end_{col}")) %>%
select(From=Time, To=end_Time, Initial=readings, End=end_readings)
From To Initial End
1 0 1 123 234
2 1 2 234 145
3 2 3 145 234
4 3 4 234 121
5 4 NA 121 NA