0

I'm new to R and so I'm hoping that someone can show me the most R-style way to accomplish what I'm trying to do.

I have JSON data which looks like this:

{
"1423699200000": 1596941,
"1423785600000": 1596941,
"1423872000000": 1596941,
"1423958400000": 1596941,
...}

The left number is a UNIX epoch timestamp and the right number is just some numerical value. I have converted this data into an R object using the rjson library. See here for details.

I want to create a line graph using this data. What is the best way to do this? I've been told that R loops which append to vectors are very slow so iterating through the values to build two vectors for the x-axis data and the y-axis data is not a good idea.

Community
  • 1
  • 1
Benjamin Gorman
  • 360
  • 1
  • 11
  • 1
    "I have converted this data into an R object using the rjson library" - please include this object or the code to reproduce it in your question. – nrussell Aug 11 '15 at 12:41

1 Answers1

3

Here's a demo using some synthesized data:

set.seed(11);
N <- 20;
jsonData <- data.frame(date=seq(as.POSIXct('2015-02-11 19:00'),by='day',len=N),num=sort(sample(seq(1596941,by=1,len=10),N,replace=T)));
jsonData;
##                   date     num
## 1  2015-02-11 19:00:00 1596941
## 2  2015-02-12 19:00:00 1596941
## 3  2015-02-13 19:00:00 1596941
## 4  2015-02-14 19:00:00 1596941
## 5  2015-02-15 19:00:00 1596942
## 6  2015-02-16 19:00:00 1596942
## 7  2015-02-17 19:00:00 1596942
## 8  2015-02-18 19:00:00 1596943
## 9  2015-02-19 19:00:00 1596943
## 10 2015-02-20 19:00:00 1596944
## 11 2015-02-21 19:00:00 1596945
## 12 2015-02-22 19:00:00 1596945
## 13 2015-02-23 19:00:00 1596945
## 14 2015-02-24 19:00:00 1596946
## 15 2015-02-25 19:00:00 1596946
## 16 2015-02-26 19:00:00 1596948
## 17 2015-02-27 19:00:00 1596949
## 18 2015-02-28 19:00:00 1596949
## 19 2015-03-01 19:00:00 1596950
## 20 2015-03-02 19:00:00 1596950
plot(num~date,data=jsonData,type='l');

plot


If you don't know how to translate your UNIX epoch timestamps to date/time values, here's how it can be done:

timestamps <- c(1423699200000,1423785600000,1423872000000,1423958400000);
dates <- as.POSIXct(timestamps/1000,origin='1970-01-01'); ## divide by 1000 to get seconds
dates;
## [1] "2015-02-11 19:00:00 EST" "2015-02-12 19:00:00 EST" "2015-02-13 19:00:00 EST" "2015-02-14 19:00:00 EST"
bgoldst
  • 34,190
  • 6
  • 38
  • 64