我认为这是有经验的程序员一直在做的事情。但是,鉴于我有限的编程经验,请耐心等待。
我有一个 Excel 文件,其中包含读取的特定单元格条目
[[{"from": "4", "response": true, "value": 20}, {"from": "8", "response": true, "value": 20}, {"from": "9", "response": true, "value": 20}, {"from": "3", "response": true, "value": 20}], [{"from": "14", "response": false, "value": 20}, {"from": "15", "response": true, "value": 20}, {"from": "17", "response": false, "value": 20}, {"from": "13", "response": true, "value": 20}]]
现在,对于每个这样的条目,我想获取每个大括号中的信息并从中生成一行数据。每个这样的行有 3 列。例如,由大括号内的第一个条目形成的行应分别具有条目“4”、“true”和“20”。我发布的部分应该给我 6 个这样的行,对于 n 个这样的重复,我最终应该得到一个 6n 行和 4 列的矩阵(一个标识符,加上提到的 3 列)。
最有效的方法是什么?我所说的“这样做”是指学习技巧,然后实现它。我的实验室可以使用相当多的软件包(Excel、Stata、Matlab、R),所以这应该不是问题。
最佳答案
这看起来像一个 JSON
样式文件。您所得到的实际上是两个数据对象的列表。我们可以使用 jsonlite 包将它们转换为 R 数据帧。试试这个:
txt <- '[[{"from": "4", "response": true, "value": 20}, {"from": "8", "response": true, "value": 20}, {"from": "9", "response": true, "value": 20}, {"from": "3", "response": true, "value": 20}], [{"from": "14", "response": false, "value": 20}, {"from": "15", "response": true, "value": 20}, {"from": "17", "response": false, "value": 20}, {"from": "13", "response": true, "value": 20}]]'
library(jsonlite)
rbind.pages(fromJSON(txt)) ## just fromJSON(txt) for the list
# from response value
# 1 4 TRUE 20
# 2 8 TRUE 20
# 3 9 TRUE 20
# 4 3 TRUE 20
# 5 14 FALSE 20
# 6 15 TRUE 20
# 7 17 FALSE 20
# 8 13 TRUE 20
如果这是在一个文件中,并且该文件被称为例如“new.txt”
,然后就可以使用
rbind.pages(fromJSON(readLines("new.txt")))
关于r - 从字符串中解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940139/