如何解决在 R 中清理下载的 pdf 数据集
我已从此 site(从“表格”选项卡)下载了 pdf 文件,并想清理 R 中的数据集并将其转换为 csv 或 excel 文件。
我正在使用 pdftools 软件包并下载了其他所需的软件包。我想专注于年龄组的数据。到目前为止,我已经使用这些代码缩小了数据集的范围。
#Load the dataset
PDF1 <- pdf_text("agegr_1-4-21.pdf") %>%
readr::read_lines() #open the PDF inside your project folder
PDF1
PDF1.grass <-PDF1[-c(1:10,17:19)] # remove lines
PDF1.grass
write.table(PDF1.grass,file="docd_pdf.csv",sep=",",row.names=FALSE)
all_stat_lines <- PDF1.grass
pdf_transpose = t(all_stat_lines)
write.table(pdf_transpose,row.names=FALSE)
df <- plyr::ldply(pdf_transpose) #create a data frame
head(df)
然而,我得到的数据框包含一个变量上的所有内容。有没有办法有效地分解数据集并为年龄组提供不同的列?我从网站下载了 pdf 文件并将其命名为 agegr_1-4-21.pdf。
我得到的输出是
解决方法
实现这一目标的一种方法是通过 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)),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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。