首页 > 解决方案 > 有什么方法:用 R 将文本转换成表格吗?

问题描述

我有一个有一些模式的字符串。

例如

>oc
[1]"for financial company payment manufacturer company payment distributor people payment other payment total payment 1 month payment 10 20 30 40 100 2 month payment 8 14 15 30 67 1 year payment 5 9 11 15 40"

原材料是表格,有一些令人不安的事情,我决定从表格中提取文本并组织,用代码清理它们然后重塑表格形式。

原料表是这样的

     for financial company payment | manufacturer company payment | distributor people payment | other..
1 m..|            10                              20                             30                 ...
2 m..|            8                               14                             15                 ...
1 y..|            5                               9                              11                ...

我很欣赏任何方法,所以请留下任何评论。这对我会有很大帮助。我也尝试做的是首先,使用 extract_text 函数(在 tabilizer 库中),其次我使用正则表达式使字符串整洁,最后我使用 scan 函数。

同样,任何方法都可以。请留下任何帮助。谢谢!

标签: rregex

解决方案


这是一个解决方案——除了优雅但有效:

您的数据:

oc <- "for financial company payment manufacturer company payment distributor people payment other payment total payment 1 month payment 10 20 30 40 100 2 month payment 8 14 15 30 67 1 year payment 5 9 11 15 40"

首先,将字符串拆分为payment

oc <- strsplit(oc, " payment ")

准备一个矩阵来填充数据:

mt <- matrix(NA, ncol = 5, nrow = 3)

oc列名中获取相关元素:

colnames(mt) <- oc[[1]][1:5]

定义行名:

rownames(mt) <- c("1 month", "2 month", "1 year")

从中获取数字oc

numbers <- ocx[[1]][7:9]

清洁numbers

numbers <- gsub("( 2 month| 1 year)", "", numbers)

现在使用from the package分解numbers成单独的数字: str_extract_allstringr

library(stringr)
numbers <- str_extract_all(numbers, "\\d+")

遍历行mt以填充来自 的数字numbers

for(i in 1:nrow(mt)){
  mt[i,] <- numbers[[i]]
}

最后重新定义mt为数据框:

mt <- as.data.frame(mt)

等等,结果:

mt
        for financial company manufacturer company distributor people other total
1 month                    10                   20                 30    40   100
2 month                     8                   14                 15    30    67
1 year                      5                    9                 11    15    40

推荐阅读