0

I currently have this data frame:

sex Dose weekReceived 1 M 1 1 2 F 2 2 3 M 3 2 4 M 1 3 5 M 1 2 6 F 2 1 7 M 1 1

and I would like this data frame:

weekReceived Dose M F 1 1 1 2 0 2 1 2 0 1 3 2 1 1 0 4 2 2 0 1 5 2 3 1 0 6 3 1 1 0

To explain the second data frame, what I am trying to do is calculate the number of males and females who have received each dose by week (e.g. for line 1 in the second data frame tells us that two males received dose 1 in week 1).

Which function do I use for this sort of reformat?

Dieu94
  • 371
  • 1
  • 11

1 Answers1

0

We get the count of all the columns, and spread the 'sex' with the frequency column 'n' to 'wide' format

library(dplyr)
df1 %>%
    count(weekReceived, Dose, sex) %>%
    spread(sex, n, fill = 0)
# A tibble: 6 x 4
#  weekReceived  Dose     F     M
#         <int> <int> <dbl> <dbl>
#1            1     1     0     2
#2            1     2     1     0
#3            2     1     0     1
#4            2     2     1     0
#5            2     3     0     1
#6            3     1     0     1

data

df2 <- structure(list(sex = c("M", "F", "M", "M", "M", "F", "M"), Dose = c(1L, 
 2L, 3L, 1L, 1L, 2L, 1L), weekReceived = c(1L, 2L, 2L, 3L, 2L, 
 1L, 1L)), class = "data.frame", row.names = c("1", "2", "3", 
 "4", "5", "6", "7"))
akrun
  • 874,273
  • 37
  • 540
  • 662