0

I have a text file consisting of 3 columns as shown below. the measurements are taken each day for several years (2001-2013). I want to plot a time series for valu1 but as the year and day are separated I have a problem:

to read the file:

  LR=read.table("C:\\Users\\dat.txt", sep ='', header =TRUE)

header:

 head(LR)
     Year day  valu1 
   1 2001   1         0     
   2 2001   2         1     
   3 2001   3         2    
   4 2001   4         0       
   5 2001   5        0.30     
   6 2001   6         0  

I tried this:

    LR$Year=as.Date(as.character(LR$Year))
    Error in `$<-.data.frame`(`*tmp*`, "Year", value = numeric(0)) : 
    replacement has 0 rows, data has .

I do not know if all days are available so I wonder if we can tell R that if a date is missing, just replace it with NA but still consider the missing date in the plot with no value in the plot.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hyat
  • 1,047
  • 4
  • 15
  • 34

1 Answers1

2

You can try:

LR$date <- as.Date(paste(LR$Year, LR$day, sep = "-"), format = "%Y-%j")

I assumed here that day is the day of the year, so something that goes from 1 - 366. This is the %j in the format.

alko989
  • 7,688
  • 5
  • 39
  • 62
  • Missing dates are just not plotted. If you are plotting a line it will interpolate between your observations, if you are plotting points you will just have a gap where you have missing observations. – alko989 Jan 30 '15 at 16:43
  • `LR$value1` has the same length as `LR$Year` and `LR$day`. If the resulting `LR$date` is `NA`, this point will not appear on the plot. – alko989 Jan 30 '15 at 16:46
  • 1
    If you do `plot(LR$date, LR$value1)` the x-axis is dates because you use `as.Date` to create the column. – alko989 Jan 30 '15 at 16:50
  • You can check the answers to [this](http://stackoverflow.com/questions/17758006/time-series-plot-with-x-axis-in-year-month-in-r) question – alko989 Feb 02 '15 at 15:04