I want to merge two rows in my dataset and create new columns according to the requirement.
Here's the dataset:
I want to merge the two rows of same area_name and date_reported and form some new columns for new_cases and old_cases.
library(dplyr)
df %>% group_by(area_name, date_reported) %>% summarise(date_reported = date_reported,
area_name = area_name, area_code = area_code, newcase= , oldcase= )
View(df)
CodePudding user response:
You would want to pivot_wider
:
library(tidyr)
df |>
pivot_wider(c(date_reported, area_name, area_code), names_from = "metric")
Output:
# A tibble: 2 × 5
date_reported area_name area_code new_cases cum_cases
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 1 37 1685
2 2 2 2 45 11044
Toy data:
df <- tibble(date_reported = c(1,1,2,2),
area_name = c(1,1,2,2),
area_code = c(1,1,2,2),
metric = rep(c("new_cases", "cum_cases"), 2),
value = c(37, 1685, 45, 11044))