Reputation: 2443
I have the following dataframe:
df -> tibble(Readmission10_LOS = c(0.55, 0.39),
Readmission10_Deceased = rep(TRUE, 2),
Readmission30_LOS = rep(NA, 2),
Readmission30_Deceased = rep(NA, 2))
I would like to "elongate" this data frame using pivot_long
in order to get to the following shape:
df_long -> structure(list(readmission = c(10, 30, 10, 30), LOS = c(0.552,
NA, 0.3, NA), Deceased = c(TRUE, NA, TRUE, NA)), row.names = c(NA,
-4L), class = c("tbl_df", "tbl", "data.frame"))
This is what I tried:
df_long <- df %>% pivot_longer(
everything(),
names_to = c(".value", "readmission"),
names_sep = "_"
)
but it does not produce the expected result.
Any ideas?
Upvotes: 0
Views: 43
Reputation: 4658
This should do the job:
df %>%
pivot_longer(everything(),
names_pattern = "readmission(\\d+)_(\\w+)",
names_to = c("readmission", ".value"))
Upvotes: 2