Reading numbers from CSV file in R with NaN present in data file
I have a CSV file, with some char fields and number fields and some NaN located in the file. I want to read numeric fields as numeric and character fields as characters.
For example, my CSV file monthly.csv
now looks like this
Datum,Index,D12,E12,b/m,tbl,AAA
187101,4.44,0.2600,0.4000,NaN,NaN,NaN
187102,4.50,0.2600,0.4000,NaN,NaN,NaN
...
...
...
I am reading this with the following code
monthly <- read.csv2("monthly.csv", sep=',', header = T, na.strings = "NaN", stringsAsFactors=F)
After reading, when I go through the contents of the variable monthly
, I still see the type as
> str(monthly)
'data.frame': 1620 obs. of 7 variables:
$ Datum : int 187101 187102 187103 187104 187105 187106 187107 187108 187109 187110 ...
$ Index : chr "4.44" "4.50" "4.61" "4.74" ...
$ D12 : chr "0.2600" "0.2600" "0.2600" "0.2600" ...
$ E12 : chr "0.4000" "0.4000" "0.4000" "0.4000" ...
$ b.m : chr NA NA NA NA ...
$ tbl : chr NA NA NA NA ...
$ AAA : chr NA NA NA NA ...
Basically only the first field gets converted to int
and the rest are still chr
. How to make others the same asint
source to share
For people who are facing the same problem, I am posting the answer that was answered in the comments ..
Changing read.csv2
to read.csv
, it worked as expected and I get the expected description.
> str(monthly)
'data.frame': 1620 obs. of 7 variables:
$ Datum : int 187101 187102 187103 187104 187105 187106 187107 187108 187109 187110 ...
$ Index : num 4.44 4.5 4.61 4.74 4.86 4.82 4.73 4.79 4.84 4.59 ...
$ D12 : num 0.26 0.26 0.26 0.26 0.26 0.26 0.26 0.26 0.26 0.26 ...
$ E12 : num 0.4 0.4 0.4 0.4 0.4 0.4 0.4 0.4 0.4 0.4 ...
$ b.m : num NA NA NA NA NA NA NA NA NA NA ...
$ tbl : num NA NA NA NA NA NA NA NA NA NA ...
$ AAA : num NA NA NA NA NA NA NA NA NA NA ...
source to share