将 PDF 转换为文本 tm 包后修复未对齐的行

Fix misaligned rows after converting PDF to text tm package

使用 R 的 tm 包,我已将 PDF table 转换为文本。我的目标是将 PDF table 转换为数据框。 PDF文件中原来的table结构为:

1. [EMPTY] , V1 , V2 , V3
2. 01-01-2015 , 1.23 , 3.45 , 5.67 
3. 02-01-2015 , 8.9 , 1.23 , 4.56

其中第一列是日期但没有列名,并且列以逗号分隔。 tm 包错误地将 table 转换为文本,导致日期列错误地向上移动:

1. 01-01-2015  ,   V1   ,  V2   ,  V3 
2. 02-01-2015 ,  1.23 ,  3.45 ,  5.67
3. 03-01-2015 ,  8.90  , 1.23  , 4.56

这样日期不再对应于正确的变量值 V1、V2 等

我需要将第一列向下移动,以便在不移动其他列的情况下正确地重新对齐日期和值。我愿意在最初将 PDF 转换为文本时使用 tm,或者在将文本转换为数据框之后使用 tm。我尝试使用 data.table 和其他工具来追求后一种策略,但没有成功。

任何人都可以提出任何策略来移动单个列的值而不移动其他列的值吗?

假设您的示例中的数据框设置不正确(第一行包含变量名称),您可以使用 dplyr 中的 lag

library(dplyr)
mydf$mydate <- lag(mydf$mydate, 1)

将 PDF 转换为数据框后,您可以通过几个步骤解决此问题。在基数 R 中:

# set column names
names(mydf) <- c("date", as.character(unlist(mydf[1, 2:4])))

# shift the date column with one row downward
mydf$date <- lag(mydf$date, 1)

# delete the unnecessary first row
mydf <- mydf[-1,]

# set the column classes in the correct format
mydf$date <- as.Date(mydf$date, format="%d-%m-%Y")
mydf[,c(2:4)] <- lapply(mydf[,c(2:4)], function(x) as.numeric(as.character(x)))

使用data.table包:

names(mydf) <- c("date", as.character(unlist(mydf[1, 2:4])))

library(data.table)
mydf <- setDT(mydf)[, date := shift(date, 1)][-1]

mydf[, date := as.Date(date, format="%d-%m-%Y")
     ][, c("V1","V2","V3") := lapply(.SD, function(x) as.numeric(as.character(x))), .SDcols = c("V1","V2","V3")]

使用的示例数据:

mydf <- read.table(text="
    01-01-2015  V1  V2  V3
    02-01-2015  1.23  3.45  5.67
    03-01-2015  8.90  1.23  4.56
", header=FALSE)