0
votes

This is a follow-up on the question: read.csv falsly converts string to integer

I have a CSV file (toy example):

V1,V2,V3
1,00010,a
2,10010,v

I want to read the second column as a string value.

I am aware of the colClasses method in the read.csv falsly converts string to integer question.

However, my data files contain 5,000+ columns with mixed variable types, while only one column is problematic. I can do something like this:

df <- read.csv("data.csv"); temp <- sapply(df,class); temp[2] <- "character"; df <- read.csv("data.csv",colClasses=temp)

But this is so ugly way of coding. Is there any more diligent way of doing this?

1
use the colClasses argument of read.csv read.csv(....., colClasses = c("numeric", "character", "character")) - onyambu

1 Answers

2
votes

You don't have to specify every column with colClasses if you use a named vector.

txt <- "V1,V2,V3
1,00010,a
2,10010,v
"

df <- read.csv(text = txt, colClasses = c(V2 = "character"))

str(df)
#> data.frame': 2 obs. of  3 variables:
#>  $ V1: int  1 2
#>  $ V2: chr  "00010" "10010"
#>  $ V3: chr  "a" "v"