【问题标题】:read mixed data into R将混合数据读入 R
【发布时间】:2015-04-07 19:54:08
【问题描述】:

我有一个文本文件 '\t' 分隔。前两列是文本,第三列是 JSON 格式,例如 {type: [{a: a1, timestamp: 1}, {a:a2, timestamp: 2}]} 如何正确放入DF?

我想将factor1\tparam1\t{type: [{a: a1, timestamp: 1}, {a:a2, timestamp: 2}]} 之类的行解析为 DF 之类的

factor_column  param_column   a_column  ts_column
    factor1        param1        a1         1    
    factor1        param1        a2         2    

【问题讨论】:

    标签: json r


    【解决方案1】:

    我已将您提供的那一行文本保存到名为“parseJSON.txt”的文件中。然后您可以像往常一样使用read.table 读取文件,然后使用library(jsonlite) 解析第三列。

    我还对文本行进行了格式化,以便在 JSON 代码周围包含引号: factor1 param1 {"type": [{"a": "a1", "timestamp": 1}, {"a":"a2", "timestamp": 2}]}

    library(jsonlite)
    
    dat <- read.table("parseJSON.txt", 
                  sep="\t", 
                  header=F,
                  quote="")
    
    #parse 3rd column using jsonlite
    js <- fromJSON(as.character(dat[1,3]))
    

    js 现在是 list

    > js
    $type
       a timestamp
    1 a1         1
    2 a2         2
    

    可以和dat的前两列合并

    res <- cbind(dat[,1:2],js$type)
    
    names(res) <- c("factor_column", "param_column", "a_column", "ts_column")
    

    给了

    > res
         factor_column param_column a_column ts_column
    1       factor1       param1       a1         1
    2       factor1       param1       a2         2
    

    【讨论】:

    • 谢谢,托斯皮格!麻烦的是我的输入文件很大,我不能像你那样手动添加引号。有什么建议如何解析 'almost-json' 行吗?
    • 我将首先检查数据是如何生成的,看看您是否可以使用 key 字符串周围的引号生成“实际”JSON。如果没有,可能有一种方法可以使用正则表达式在字母数字字符串周围加上引号,但这是另一个问题
    • @crusoe This question 可用于提取文本以添加引号?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2011-03-29
    相关资源
    最近更新 更多