0

I have daily device exposure data which I would like to transform to weekly data. I know this question has been asked before but i cannot figure this out as I'm very new to R.

How can I transform this into weekly counts by county code (there are 88 total) and sum the device exposure, total devices in county, adjusted exposure and adjusted total number of devices by week?

  • welcome to StackOverflow! Can you please edit your question to include your sample data as (code-formatted, i.e. by surrounding it in "code fences" -- triple-backquotes) cut-and-pasted text, rather than a screenshot? Or, use `dput()` to include a sample of your data (see https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example ) – Ben Bolker Oct 24 '20 at 21:23
  • Also: what have you tried/found so far? https://stackoverflow.com/questions/40554231/dplyr-lubridate-how-to-aggregate-a-dataframe-by-week/40554522 – Ben Bolker Oct 24 '20 at 21:24
  • I appreciate the attempt to modify your question as I requested, but that's not at all what I meant - for example, see this recent question: https://stackoverflow.com/questions/64517896/adding-a-column-to-a-data-frame-with-two-different-variables – Ben Bolker Oct 24 '20 at 22:12

1 Answers1

1

Try this using dplyr and lubridate. Use week to extract the week after properly formating the date, then group by county and week and use summarise() to obtain the desired variables. Here the code (not tested as no data is shared). Also pay attention to what @BenBolker said about reproducible questions.

library(dplyr)
library(lubridate)
#Code
df %>% mutate(date=as.Date(date,'%m/%d/%y'),
              Week=Week(date)) %>% select(-date) %>%
  group_by(county,Week) %>%
  summarise(Count=n(),
            DevExp=sum(dex,na.rm=TRUE),
            NumDev=sum(num_devices,na.rm=TRUE),
            Adexp=sum(dex_a,na.rm=TRUE),
            NumDevA=sum(num_devices_a,na.rm=TRUE))
Duck
  • 39,058
  • 13
  • 42
  • 84