Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

time series - How to get the lowest value per interval in R

I have data in the zoo format in the following structure

date           val
2020-11-01     3244
2020-11-02     3273
2020-11-03     2974
2020-11-04     3283
2020-11-05     3922
2020-11-06     3669
2020-11-07     4246
2020-11-08     4594
2020-11-09     4086
2020-11-10     4302
2020-11-11     4559
2020-11-12     4981
2020-11-13     4741
2020-11-14     5267


that I am trying to get into this form

    date           val
Mon 2020-11-01     3244
Tue 2020-11-02     3273
Wed 2020-11-03     2974
Thu 2020-11-04     3283
Fri 2020-11-05     3922
Sat 2020-11-06     3669
Sun 2020-11-07     4246
Mon 2020-11-08     4594
Tue 2020-11-09     4086
Wed 2020-11-10     4302
Thu 2020-11-11     4559
Fri 2020-11-12     4981
Sat 2020-11-13     4741
Sun 2020-11-14     5267

In order to count the number of time I observe the smallest of the values per week.

Mon = 1
Tue = 1
Wed = 0
Thu = 0
Fri = 0
Sat = 0
Sun = 0

I tried to let the data in the flat format before adding the date with zoo and added the weekdays but failed to count with it. Does anyone know an easier way to do it? I am open to visual solutions

question from:https://stackoverflow.com/questions/65649498/how-to-get-the-lowest-value-per-interval-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following should do the trick:

library(lubridate)
df$day <- weekdays(as.Date(df$date))

# Note: 
# There is one way to define a week
df$week <- week(df$date)
# And there is also another. Make sure to pick. 
df$isoweek <- isoweek(df$date)

df <- df %>% group_by(isoweek) %>% mutate(min_here = val == min(val))

df %>% group_by(day) %>% summarise(sum(min_here))

# A tibble: 7 x 2
  day       `sum(min_here)`
  <chr>               <int>
1 Friday                  0
2 Monday                  1
3 Saturday                0
4 Sunday                  1
5 Thursday                0
6 Tuesday                 1
7 Wednesday               0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...