如果后跟 R 中的空行,则将多行数据帧合并在一起
Merge multiple rows of dataframe together if followed by an empty row in R
我有以下数据框:
location <- "https://www.mofa.go.jp/announce/info/conferment/pdfs/2013_sp.pdf"
out <- tabulizer::extract_tables(location)
final <- do.call(rbind, out)
final <- as.data.frame(final) %>%
janitor::row_to_names(row_number = 2) %>%
janitor::clean_names()
不幸的是,由于 tabulizer::extract_table
(see this thread) 的提取问题,数据帧不干净。
一个数据点跨越多行,后面是空行(屏幕截图中的第 20 和 26 行):
如果多行之后有空行(或者如果之后没有行,如数据框的最后一行),是否可以自动将多行合并为一行?
也就是说,第13-19行应该是单行,21-25行也应该是单行。列是正确的。
非常感谢您的帮助!
数据很乱,因为同一组之间可以有空行(第 126 和 127 行)。我已经定义了 decoration != ""
时的组开始。用国籍定义组会更容易,因为它有(
(问题是来自台湾的人)。
library(tidyverse)
library(data.table)
tidyPage <- function(dt){
setDT(dt)
dt <- dt[, map(.SD, as.character)]
dt[, flag := !decoration == ""]
dt <- dt[which.max(flag):.N]
dt[, group := rleid(flag)]
dt[flag == TRUE, flag := c(TRUE, rep(FALSE, .N - 1)), by = group]
dt[, group := cumsum(flag)]
split(dt, dt$group) %>%
map_dfr(~map_chr(select(.x, -flag, -group), str_c, collapse = " ")) %>%
mutate(across(where(is.character), str_squish))
}
location <- "https://www.mofa.go.jp/announce/info/conferment/pdfs/2013_sp.pdf"
out <- tabulizer::extract_tables(location) %>%
map(~
as.data.frame(.x) %>%
janitor::row_to_names(row_number = 2) %>%
janitor::clean_names()
) %>%
map_dfr(tidyPage)
我有以下数据框:
location <- "https://www.mofa.go.jp/announce/info/conferment/pdfs/2013_sp.pdf"
out <- tabulizer::extract_tables(location)
final <- do.call(rbind, out)
final <- as.data.frame(final) %>%
janitor::row_to_names(row_number = 2) %>%
janitor::clean_names()
不幸的是,由于 tabulizer::extract_table
(see this thread) 的提取问题,数据帧不干净。
一个数据点跨越多行,后面是空行(屏幕截图中的第 20 和 26 行):
如果多行之后有空行(或者如果之后没有行,如数据框的最后一行),是否可以自动将多行合并为一行?
也就是说,第13-19行应该是单行,21-25行也应该是单行。列是正确的。
非常感谢您的帮助!
数据很乱,因为同一组之间可以有空行(第 126 和 127 行)。我已经定义了 decoration != ""
时的组开始。用国籍定义组会更容易,因为它有(
(问题是来自台湾的人)。
library(tidyverse)
library(data.table)
tidyPage <- function(dt){
setDT(dt)
dt <- dt[, map(.SD, as.character)]
dt[, flag := !decoration == ""]
dt <- dt[which.max(flag):.N]
dt[, group := rleid(flag)]
dt[flag == TRUE, flag := c(TRUE, rep(FALSE, .N - 1)), by = group]
dt[, group := cumsum(flag)]
split(dt, dt$group) %>%
map_dfr(~map_chr(select(.x, -flag, -group), str_c, collapse = " ")) %>%
mutate(across(where(is.character), str_squish))
}
location <- "https://www.mofa.go.jp/announce/info/conferment/pdfs/2013_sp.pdf"
out <- tabulizer::extract_tables(location) %>%
map(~
as.data.frame(.x) %>%
janitor::row_to_names(row_number = 2) %>%
janitor::clean_names()
) %>%
map_dfr(tidyPage)