1

I am reading a csv file into a dataframe in R. The first column contains dates and the following 50 columns contain floats. I am having trouble coercing the 50 columns to numeric type vs. character. First, I try using the colClasses argument:

data <- read.csv(paste("regional_data_",term,".csv", sep=""), colClasses=c("character", rep("numeric", 50)))
head(data)

  | date       | Illinois | Delaware | ...
1 | 2015-10-31 |  419.34  |  632.72  | ...
2 | 2015-11-30 |  513.21  |  507.43  | ...
3 | 2015-12-31 |  629.86  |  623.72  | ...
...

However, when I check the types, they appear to be 'character'.

apply(data , 2, mode)

date      'character'
Illinois  'character'
Delaware  'character'
...

Further, I tried coercing the latter 50 columns to numeric type, but this did not work either.

data[,-1] <- apply(data[,-1], 2, function(x) as.numeric(x))

apply(data , 2, mode)

date      'character'
Illinois  'character'
Delaware  'character'
...

What am I doing wrong? The characters are preventing me from using binary operations on my data.

Melanie
  • 1,787
  • 3
  • 12
  • 15
  • 1
    Have you considered using read.table() and set stringsAsFactors = FALSE and sep = "," ? – USER_1 Nov 21 '16 at 16:05
  • I just tried `data <- read.table(paste("regional_data_",term,".csv", sep=""), header=TRUE, stringsAsFactors = FALSE, sep=",", colClasses = c("character", rep("numeric", 50)))` and I am still getting characters. – Melanie Nov 21 '16 at 16:14
  • If your file is generated in Excel it is possible Excel is messing up the decimal symbol or something similar. – USER_1 Nov 21 '16 at 16:23
  • Here is a related question: http://stackoverflow.com/questions/13706188/importing-csv-file-into-r-numeric-values-read-as-characters – USER_1 Nov 21 '16 at 16:24
  • Your data are being read in correctly, but `apply` is not the right function; `apply` is for use with data in matrix form. Use `sapply(data, class)` and you'll get the correct values. `lapply` will work, too, but it returns a list. – Edward Carney Nov 21 '16 at 16:37
  • You are referring to the line where I check the classes? Changing this from `apply` to `sapply` only changes the class check, not the actual type conversion. I tried your suggestion though anyways and it is still showing character. – Melanie Nov 21 '16 at 18:07

0 Answers0