r - 有什么方法:用 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 函数。
同样,任何方法都可以。请留下任何帮助。谢谢!
解决方案
这是一个解决方案——除了优雅但有效:
您的数据:
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_all
stringr
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
推荐阅读
- javascript - 为什么我不能使用 AWS 开发工具包 sendEmail 向多个地址发送邮件?
- hazelcast - Hazelcast IMap TTL 到期
- python-3.x - 使用Python从soap请求返回的xml中提取数据以保存到csv
- python - 如何将输入图像数组从 1d 重塑为 3d
- c# - 在 Windows ML 中将 Image 转换为 TensorFloat(用于转换后的 Keras 模型)
- pyspark - RandomForestClassifier 没有属性变换,那么如何得到预测呢?
- python - 如何将数据框与另一个包含标量值计数的数据框连接起来?
- c# - 反序列化 CouchBase 响应时,JsonConvert.DeserializeObject 抛出异常
- python - 获取 NumPy 数组中切片的相对位置
- javascript - 在页面呈现 react-native 钩子之前从 api 获取数据