实现此目的的一种方法是通过tidyr::extract
. 我首先从第一行中提取标题,然后从其他行中提取数据。
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
数据对于数据,我下载了其中一张表并使用您的代码对其进行了清理。
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))