【问题标题】:Split and transform a R character string into numerical vector将 R 字符串拆分并转换为数值向量
【发布时间】:2012-01-30 02:36:11
【问题描述】:

我想转换以下 json 并将值放入数据框中。它几乎可以工作,但 as.data.frame() 将所有内容放在一行中。

require(rjson)
require(RCurl)

y = getURI(url1)
y
[1] "[{\"close\":5.45836392962902,\"highest\":5.45837200714172,\"lowest\":5.45836392962902,\"open\":5.45837200714172,\"start_time\":\"2012-01-29T18:29:24-08:00\"},{\"close\":5.45837200714172,\"highest\":5.45837200714172,\"lowest\":5.45834791002201,\"open\":5.45835598753471,\"start_time\":\"2012-01-29T18:28:24-08:00\"}]"

x = fromJSON(y)
> str(x)
List of 2
 $ :List of 5
  ..$ close     : num 5.46
  ..$ highest   : num 5.46
  ..$ lowest    : num 5.46
  ..$ open      : num 5.46
  ..$ start_time: chr "2012-01-29T18:29:24-08:00"
 $ :List of 5
  ..$ close     : num 5.46
  ..$ highest   : num 5.46
  ..$ lowest    : num 5.46
  ..$ open      : num 5.46
  ..$ start_time: chr "2012-01-29T18:28:24-08:00"

as.data.frame(x)
     close  highest   lowest     open                start_time  close.1 highest.1 lowest.1   open.1              start_time.1
1 5.458364 5.458372 5.458364 5.458372 2012-01-29T18:29:24-08:00 5.458372  5.458372 5.458348 5.458356 2012-01-29T18:28:24-08:00

而不是在一排。我希望它们分成两排。

   close    highest   lowest     open                start_time  
1 5.458364  5.458372 5.458364 5.458372 2012-01-29T18:29:24-08:00 
2 5.458372  5.458372 5.458348 5.458356 2012-01-29T18:28:24-08:00

我可以在 as.data.table 中指定一些东西来让它工作吗?

编辑:

do.call(rbind,lapply(x,as.data.frame))

上面能够将其强制转换为数据框,但时间戳列有两个因素。下一部分有自己的问题here

y = do.call(rbind,lapply(x,as.data.frame))
str(x)
'data.frame':   2 obs. of  5 variables:
 $ close     : num  5.46 5.46
 $ highest   : num  5.47 5.46
 $ lowest    : num  5.46 5.46
 $ open      : num  5.46 5.46
 $ start_time: Factor w/ 2 levels "2012-01-29T21:48:24-05:00",..: 1 2

如果我尝试转换我得到的 POSIX 格式

 x$start_time = as.POSIXct(x$start_time)
 x$start_time
[1] "2012-01-29 CST" "2012-01-29 CST"

但它会丢失时间数据。

【问题讨论】:

    标签: json r curl rcurl


    【解决方案1】:

    你可以试试:

    do.call(rbind,lapply(x,as.data.frame))
    

    【讨论】:

    • 当我这样做时,start_time 列有 2 个因素。知道如何以 POSIX 格式获取它吗?
    • @Kevin as.POSIXct? as.POSIXlt?阅读并选择。
    • 我试过了。日期是正确的,但它似乎去掉了时间。当我使用 as.POSIXlt 时,它给了我错误的时间。
    • @Kevin 这些功能无法读心。你的时间格式我看不出来。您必须告诉as.POSIXct 您的时间是如何格式化的,才能正确读取。我建议你仔细阅读?asPOSIXct,特别注意strptime
    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多