R error in plot.window(…) need finite ‘xlim’ values

plotr

I want to plot a data.frame and my problem is, that the following error appears:

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

This is my code:

CO2.data = read.table("962RecordedDataCO2.txt",sep=";", stringsAsFactors=F)

x = CO2.data$V1
y = CO2.data$V2

plot(x,y,type="l")

I thought the problem might be, that x and y are character values and this cannot be plotted (x are dates and times for example 16.06.2015 20:07:00 and y just a double value like 0,0300). But I couldn't really do y = as.numeric(CO2.data$V2) because then every value was NA.

The result of str(CO2.data) is:

'data.frame':   24479 obs. of  2 variables:
 $ V1: chr  "15.06.2015 00:01:00" "15.06.2015 00:02:00" "15.06.2015 00:03:00" "15.06.2015 00:04:00" ...
 $ V2: chr  "0,0200" "0,0200" "0,0200" "0,0200" ...

Best Answer

But I couldn't really do y = as.numeric(CO2.data$V2) because then every value was NA.

Well plot essentially has the same problem.

When reading in data, the first step should always be to put the data into an appropriate format, and only then process to the next step. Your workflow should always look like this, with virtually no exceptions.

In your case, you need to convert the datetime and the numeric values explicitly because R cannot handle the format conversion automatically:

x = strptime(CO2.data$V1, '%d.%m.%Y %H:%M:%S')
y = as.numeric(sub(',', '.', CO2.data$V2))

In particular, you need to specify the date format (first line) and you need to convert decimal commas into decimal points before converting the strings to numbers.

If you use read.csv2 instead of read.table, you can specify the decimal separator; this allows you to omit the second conversion above:

CO2.data = read.csv2("962RecordedDataCO2.txt", sep=";", dec = ",", stringsAsFactors=FALSE)

Oh, and use FALSE and TRUE, not F and T — the latter are variables, so some code could redefine the meaning of F and T.

Related Topic