Carsten
Carsten

Reputation: 37

Importing csv file to R - factors read as characters

New to R. When importing a csv file columns are being read as characters when they are in fact - or should be - factors. All three columns in question have only two levels (yes/no and male/female).

My attempt: In the Import Text Data dialog box I change the the columns to factor by inserting a comma separated list of factors.

> LungCapDataCSVnew <- read_csv("~/file.csv", 
  col_types = cols(Caesarean = col_factor(levels = c("no", 
  "yes")), Gender = col_factor(levels = c("male", 
  "female")), Smoke = col_factor(levels = c("no", 
  "yes"))))

> View(file)

> class(Gender)
[1] "character"

> class(Smoke)
[1] "character"

As it shows, 'Gender' and 'Smoke' columns read as characters when they should be factors.

How to solve this?

Upvotes: 0

Views: 2446

Answers (3)

Caitriona
Caitriona

Reputation: 1

As I have just discovered: read.csv seems to detect factors and levels read_csv does not, it just assigns the column heading as a character.

Upvotes: -2

iskandarblue
iskandarblue

Reputation: 7526

It's strange that simply read.csv() without any extra arguments doesn't automatically read in your characters as factors.

After importing the file with file <- read.csv("~/file.csv") you can try

i <- sapply(file, is.character)
file[i] <- lapply(file[i], as.factor)

To convert all character columns into factors

Upvotes: 1

Shashank
Shashank

Reputation: 533

Use can change character into factor

LungCapDataCSVnew$Smoke<-as.factor(LungCapDataCSVnew$Smoke)
LungCapDataCSVnew$Gender<-as.factor(LungCapDataCSVnew$Gender)

New to R . Suggesting website- http://cran.r-project.org/manuals.html

Thanks

Upvotes: 0

Related Questions