0

I added spaces around my fields in CSV file in Vim csv.vim plugin. Now, I am having difficulties in declaring the column classes as numerical (num etc). Having negative values there also cause problems in the following columns The data can have empty fields. Data data.csv

Test, test2, test3
    , 1    , 1
10.8, -1   , 1
1.1 , 2    , 2

Code

library('methods')
DF <- read.csv("/home/masi/Data/data.csv", header = T, sep = ",", colClasses=c('num','num'))

DF

Output

Error in methods::as(data[[i]], colClasses[i]) : 
  no method or default for coercing “character” to “num”
Calls: read.csv -> read.table -> <Anonymous>
Execution halted
  • Casting to numerical fails when doing colClasses=c('num','num').
  • Output in Column 3 is considered as NA because of one minus mark (-1) in the second column.

R: 3.3.3

  • I don't know anything about R, but is it possible that the importer is complaining about the "character" (non-numeric) header line? – Jeff Schaller May 7 '17 at 17:28
  • 1
    @JeffSchaller I think it is not the case because I have header = T. – Léo Léopold Hertz 준영 May 7 '17 at 17:29
1

AFAIK num is not a valid atomic vector class in R:

Possible values are NA (the default, when type.convert is used), "NULL" (when the column is skipped), one of the atomic vector classes (logical, integer, numeric, complex, character, raw), or "factor", "Date" or "POSIXct". Otherwise there needs to be an as method (from package methods) for conversion from "character" to the specified formal class.

Your code should work if you replace it by numeric:

> DF <- read.csv("data.csv", header = T, sep = ",", colClasses=c('num','num'))Error in methods::as(data[[i]], colClasses[i]) : 
  no method or default for coercing “character” to “num”

whereas

> DF <- read.csv("data.csv", header = T, sep = ",", colClasses=c('numeric','numeric'))
> 
> DF
  Test test2 test3
1   NA     1     1
2 10.8    -1     1
3  1.1     2     2
> 
  • My mistake. It is strange that the shorthand of TRUE as T is accepted, but not of other types etc num for numeric. – Léo Léopold Hertz 준영 May 7 '17 at 18:13
1

Try the readr package with argument trim_ws=TRUE in read_delim():

R> readr::read_delim("data.csv", delim=",", col_types="dii", trim_ws=TRUE)
# A tibble: 3 × 3
   Test test2 test3
  <dbl> <int> <int>
1    NA     1     1
2  10.8    -1     1
3   1.1     2     2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.