The end result isn't quite what you asked for, as its more succinct. I prefer to have 3 columns for the 3 possible speeds at the differing times, rather than 6 columns where 3 serve as a key to label the other 3
example_df <- function(intext) {
tf <- tempfile()
writeLines(intext, con = tf)
require(tidyverse)
as_tibble(read.delim(tf))
}
(df <- example_df("
ID Time Speed
101 AM 8
101 PM 6
101 IP 9
102 AM 7
102 N/A N/A
102 N/A N/A
103 AM 7
103 IP 6
103 PM 8") %>%
mutate(Speed=as.integer(Speed)) %>%
filter(!is.na(Speed)) %>%
distinct)
pivot_wider(df,id_cols = ID,
names_from = Time,
names_prefix = "Speed_at_time_",
values_from = Speed
)
# A tibble: 3 x 4
ID Speed_at_time_AM Speed_at_time_PM Speed_at_time_IP
<int> <int> <int> <int>
1 101 8 6 9
2 102 7 NA NA
3 103 7 8 6