0

I wish to transform part of a dataframe to take on of the columns values and append it to the column names. An example of what I have is shown below:

dates <- c("2020-01-01", "2020-01-02", "2020-01-02")
gender <- c("Male","Male","Female")
Age <- c("Eighteen","NineTeen","Twenty")
Count <- c(1,2,1)

Data <- data.frame(dates,gender,Age,Count)

Output:

enter image description here

Desired Example DF:

dates <- c("2020-01-01", "2020-01-02", "2020-01-02")
gender <- c("Male","Male","Female")
Eighteen <- c(1,0,0)
Nineteen <- c(0,2,0)
Twenty <- c(0,0,1)

Data2 <- data.frame(dates,gender,Eighteen,Nineteen,Twenty)

Desired Output:

enter image description here

Machavity
  • 30,841
  • 27
  • 92
  • 100
Tolki
  • 63
  • 1
  • 1
  • 9
  • 1
    `tidyr::pivot_wider(Data, names_from = Age, values_from = Count, values_fill = list(Count = 0))` – Ronak Shah Feb 20 '20 at 00:48
  • `dcast(as.data.table(Data), dates + gender ~ Age, value.var = "Count", fill = 0)` (using the `data.table` package) – r2evans Feb 20 '20 at 00:52

0 Answers0