R 通过在不同列上匹配条件来分配ID
大家好,我想为下面的数据帧分配一个ID。 如果到达站与出发站匹配,且到达时间与出发时间匹配,则公交车必须相同。 有人知道如何解决这个问题吗? 提前谢谢 我希望有以下资料:R 通过在不同列上匹配条件来分配ID,r,R,大家好,我想为下面的数据帧分配一个ID。 如果到达站与出发站匹配,且到达时间与出发时间匹配,则公交车必须相同。 有人知道如何解决这个问题吗? 提前谢谢 我希望有以下资料: 一种方法是创建一个graph对象,其中复合键站、时间戳表示一个graph顶点,每条路由表示一条边。从该图中,每个连接代表一个唯一的路由,因此在您的示例中有两个组件: Component 1: (Station1 10:10) -> (Station2 10:15) -> (Station3 10:18) ->
一种方法是创建一个graph对象,其中复合键站、时间戳表示一个graph顶点,每条路由表示一条边。从该图中,每个连接代表一个唯一的路由,因此在您的示例中有两个组件:
Component 1: (Station1 10:10) -> (Station2 10:15) -> (Station3 10:18) -> (Station4 10:20)
Component 2: (Station10 10:12) -> (Station 10:25)
在这里使用igraph和Tidyverse包dplyr、magrittr和tibble,可以实现如下方法:
# df is source data. create a composite key for
# arrival and departure by concatenating station
# name and timestamp
df %<>% mutate(arrkey = paste0(From, Departure),
depkey = paste0(To, Arrival));
# create graph, identify clusters, and convert clusters to data frame
components <- graph_from_data_frame(df %>% select(arrkey, depkey)) %>%
components() %>%
`$`('membership') %>%
as.data.frame() %>%
tibble::rownames_to_column() %T>%
{names(.) <- c('vertexkey','component')}
# join components with original data frame to produce output
df %>% inner_join(components, by=c('arrkey'='vertexkey')) %>%
select(ID=component, everything()) %>%
select(-arrkey, -depkey) %>%
arrange(ID, Departure)
注意:为了简单起见,我使用以下代码生成df,删除了出发/到达日期:
df <- data.frame(
From=c('Station1', 'Station10', 'Station2', 'Station3'),
To=c('Station2', 'Station15', 'Station3', 'Station4'),
Departure = c('10:10','10:12','10:15','10:18'),
Arrival = c('10:15','10:25','10:18','10:20'));
请包括一个小的可复制的例子以及预期的输出。请阅读相关信息以及如何给出建议。这将使其他人更容易帮助你。
df <- data.frame(
From=c('Station1', 'Station10', 'Station2', 'Station3'),
To=c('Station2', 'Station15', 'Station3', 'Station4'),
Departure = c('10:10','10:12','10:15','10:18'),
Arrival = c('10:15','10:25','10:18','10:20'));