dat <- structure(list(ID = c(21785L, 21785L, 21785L), HR1 = c(0.828273303,
6.404590021, 0.775568448), Weekday1 = c(2L, 3L, 2L), HR2 = c(NA,
1.122899914, 0.850113234), Weekday2 = c(NA, 4L, 3L), HR3 = c(NA,
0.866757168, 0.868943246), Weekday3 = c(NA, 5L, 4L), HR4 = c(NA,
0.563804788, 0.728656328), Weekday4 = c(NA, 6L, 5L), HR5 = c(NA,
0.888109208, 0.823803733), Weekday5 = c(NA, 7L, 6L), HR6 = c(NA,
0.578834113, 0.863467391), Weekday6 = c(NA, 1L, 7L), HR7 = c(NA,
NA, 0.939920869), Weekday7 = c(NA, 2, 8)), row.names = c(5L,
163L, 167L), class = "data.frame")
library(dplyr)
library(tidyr)
dat %>% pivot_longer(-ID,
names_to = c(".value", "Num"), # names_to = c(".value", NA),
names_pattern = "(\\D+)(\\d+)") %>%
drop_na %>% # would not need this line if NA in names_to were allowed
select(-Num) # would not need this line if NA in names_to were allowed
In the example below taken from https://stackoverflow.com/questions/58566740/pivot-by-group-for-unequal-data-size/58567045#58567045 we don't need the
Numcolumn so it would be nice to be able to specifyNAinstead of giving a dummy name. Also because that column is generatedvalues_drop_na=TRUEwon't eliminateNArows and we need to add additional statements (drop_na,select) to drop them and remove that column. These could have been eliminated had NA components been available.