One approach to achieve this is via tidyr::extract
. I first extract the header from the first row and second extract the data from the other rows.
library(dplyr)
regex_header <- paste0(
"^(\w+)\s+",
paste(rep("(\d+\-\d+ years)", 7), collapse = "\s+"), "\s+",
"(\d+\+ years)\s+",
"(\w+)"
)
header <- tidyr::extract(data = slice(df, 1), col = V1, into = paste0("var", 1:10), regex = regex_header) %>%
t() %>%
.[, 1]
regex_body <- paste0("^([\w\*]+)\s+", paste(rep("([\d,\.]+)", 9), collapse = "\s+"))
tidyr::extract(data = slice(df, 2:nrow(df)), col = V1, into = header, regex = regex_body)
#> Outcome 0-17 years 18-29 years 30-39 years 40-49 years 50-59 years
#> 1 Case 2.090 3.435 2.706 2.190 1.887
#> 2 Hospitalized 20 81 133 188 264
#> 3 Died 0 4 4 11 36
#> 4 Missing** 612 1.740 1.369 1.076 1.013
#> 5 Gesamtsumme 2.722 5.260 4.212 3.465 3.200
#> 60-69 years 70-79 years 80+ years Gesamtsumme
#> 1 1.218 504 224 14.254
#> 2 299 219 151 1.355
#> 3 58 83 110 306
#> 4 674 295 208 6.987
#> 5 2.249 1.101 693 22.902
DATA For the data I downloaded one of the tables and cleaned it using your code.
df <- structure(list(V1 = c(
"Outcome 0-17 years 18-29 years 30-39 years 40-49 years 50-59 years 60-69 years 70-79 years 80+ years Gesamtsumme",
"Case 2.090 3.435 2.706 2.190 1.887 1.218 504 224 14.254",
"Hospitalized 20 81 133 188 264 299 219 151 1.355",
"Died 0 4 4 11 36 58 83 110 306",
"Missing** 612 1.740 1.369 1.076 1.013 674 295 208 6.987",
"Gesamtsumme 2.722 5.260 4.212 3.465 3.200 2.249 1.101 693 22.902"
)), class = "data.frame", row.names = c(NA, -6L))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…