[英]R : Pivot hourly data to columns
I am pretty new to r and I am trying to manipulate bus schedule data.我是 r 的新手,我正在尝试操纵公交时刻表数据。 I would like to display the times following the picture attached
我想按照附图显示时间
.
.
I managed to go from 1. to 2. but I am now struggling to get to 3.我设法从 1. 到 2. go,但我现在正在努力达到 3.
Here is my code so far:到目前为止,这是我的代码:
#1
timetable <- as.data.frame(c("11:34","11:46","12:12","13:16","14:45","15:54","16:22"))
colnames(timetable) <- 'time'
#2
library(stringr)
new.timetable <- str_split_fixed(timetable$time,":",2) %>% as.data.frame()
colnames(new.timetable) <- c('Hours', 'Minutes')
#3 ??
Is there a way to place Hours as columns and to get the minutes as the data under it?有没有办法将小时作为列放置并将分钟作为其下的数据?
Thank you very much for your help.非常感谢您的帮助。 Best,
最好,
Do this serve your purpose?这是否符合您的目的?
#I have added one value to your timetable object
timetable <- as.data.frame(c("11:34","11:46","12:12","13:16","14:45","15:54","16:22", "11:47")) # added one value
library(tidyverse)
#3.
new.timetable %>%
group_by(Hours) %>%
mutate(id = row_number())%>%
ungroup() %>%
pivot_wider(id_cols=id, names_from = Hours, values_from = Minutes, values_fn = list) %>%
select(-id) %>%
unnest(1:6)
# A tibble: 3 x 6
`11` `12` `13` `14` `15` `16`
<chr> <chr> <chr> <chr> <chr> <chr>
1 34 12 16 45 54 22
2 46 NA NA NA NA NA
3 47 NA NA NA NA NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.