Error while creating a Timeseries plot in R: Error

2019-09-10 11:56发布

问题:

Here's a sample of my single column data set:

Lines 
141,523
146,785
143,667
65,560
88,524
148,422

I read this file as a .csv file, convert it into a ts object and then plot it:

##Read the actual number of lines CSV file

Aclines <- read.csv(file.choose(), header=T, stringsAsFactors = F)

Aclinests <- ts(Aclines[,1], start = c(2013), end = c(2015), frequency = 52)

plot(Aclinests, ylab = "Actual_Lines", xlab = "Time", col = "red")

I get the following error message:

Error in plot.window(xlim, ylim, log, ...) : need finite 'ylim' values
In addition: Warning messages:
1: In xy.coords(x, NULL, log = log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

I thought this might be because of the "," in the columns and tried to use sapply to take care of that as advised here:

need finite 'ylim' values-error

plot(sapply(Aclinests, function(x)gsub(",",".",x)))

But I got the following error:

Error in plot(sapply(Aclinests, function(x) gsub(",", ".", x))) : 
  error in evaluating the argument 'x' in selecting a method for function 'plot': Error in sapply(Aclinests, function(x) gsub(",", ".", x)) : 
  'names' attribute [105] must be the same length as the vector [1]

Here is the head of my original and ts data set if it might help:

> head(Aclines)
    Lines
1 141,523
2 146,785
3 143,667
4  65,560
5  88,524
6 148,422
> head(Aclinests)
[1] "141,523" "146,785" "143,667" "65,560"  "88,524"  "148,422"

Also, if I read the .csv file as:

Aclines <- read.csv(file.choose(), header=T, **stringsAsFactors = T**)

Then, I am able to plot the ts object, but head(Aclinests)gives the below output which is not consistent with my original data:

> head(Aclinests)
[1] 14 27 17 84 88 36

Please advice on how I can plot this ts object.

回答1:

The simplest way to avoid this, in my case, is to remove the commas in the excel file containing the data. This can be done using simple excel commands and it worked for me.