2012-01-30 66 views
0

我想轉換下面的json並將值放入數據框中。它幾乎可以工作,但as.data.frame()將所有內容放在一行中。將R字符串拆分並轉換爲數值向量

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" 

但它失去的時間數據。

回答

2

您可以試試:

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

的START_TIME列有2個因素,當我做到這一點的方式。任何想法如何獲得POSIX格式? – Kevin 2012-01-30 03:07:54

+0

@Kevin'as.POSIXct'? 'as.POSIXlt'?閱讀並選擇你的選擇。 – joran 2012-01-30 03:36:14

+0

我試過了。日期是正確的,但它似乎剝奪了時間。當我使用as.POSIXlt時,它給了我錯誤的時間。 – Kevin 2012-01-30 03:42:07