想象以下数据框的片段:
ID ActivityName Time Type Shape
1 1 Request 0.000 Type_1 767
2 1 Request 600.000 Type_1 767
3 1 Start 600.000 Type_1 1376
4 1 Start 600.000 Type_1 1376
5 1 Schedule Activities 600.000 Type_1 15
6 1 Schedule Activities 2062.295 Type_1 15
我想做的是基于ActivityName中的重复条目创建两个新列。
特别是,我想将同一活动的后两行合并为具有开始和完整时间戳(以秒为单位的Time)的一行。
鉴于ActivityName中的不是全部条目具有匹配的第二个条目(但是,最多两个连续的条目相同),我也想删除这样的“单身”行。
P.s。尽管从数据帧摘要中并不明显,但是ActivityName的所有级别在该列中都发生了很多次,无论是以连续相同的方式还是以单一方式。
任何有关解决此问题的想法将受到高度赞赏。
这样的事情?
df<-data.frame(activity_name = c("A", "A", "B", "B", "C", "C"),
time = c(0,2,2,4,4,6))
df
activity_name time 1 A 0 2 A 2 3 B 2 4 B 4 5 C 4 6 C 6
library(tidyverse)
df %>%
group_by(activity_name) %>%
summarise(StartTime = first(time),
EndTime = last(time))
activity_name StartTime EndTime <fct> <dbl> <dbl> 1 A 0 2 2 B 2 4 3 C 4 6
也许像这样:
library(tidyverse)
df %>%
group_by(ID, ActivityName) %>%
filter(n() > 1) %>%
mutate(TimeCat = if_else(row_number() == 1, "Start", "Complete")) %>%
pivot_wider(id_cols = c(ID, ActivityName, Type, Shape), names_from = TimeCat, values_from = Time)
输出
# A tibble: 3 x 6
# Groups: ID, ActivityName [3]
ID ActivityName Type Shape Start Complete
<int> <chr> <chr> <int> <dbl> <dbl>
1 1 Request Type_1 767 0 600
2 1 Start Type_1 1376 600 600
3 1 Schedule_Activities Type_1 15 600 2062.