I have a some test data with two columns. The column "hour" shows hourly values (p.m.). The column "day" indicates the corresponding day, i.e. on day 1 there are hourly values from 7 to 11 o'clock.
I now want to calculate how big the time span is for each day and store these values in a vector.
Something like:
timespan <- c(5,7,3)
How could I calculate this in a loop? I thought about something like length(unique...)
Thanks in advance!
Here is the code:
day <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)
hour <- c(7,7,8,10,11,5,6,6,7,11,9,10,10,11,11)
df <- data.frame(day,hour)
CodePudding user response:
library(dplyr)
df %>%
group_by(day) %>%
summarise(time_span = max(hour) - min(hour) 1)
## A tibble: 3 x 2
# day time_span
# <dbl> <dbl>
# 1 1 5
# 2 2 7
# 3 3 3