I have seen many code samples which use the setting while reading data:

train <- read.csv('train.csv', stringsAsFactors = F)
test  <- read.csv('test.csv', stringsAsFactors = F)

From a little search I understand that it prevents conversion of string to factors and treats them as vectors.

But what are factors and why are they required?

Vectors should have same datatype , logically string is one , so why convert string fields to factors?

When do you use stringsAsFactors = T ?


2 Answers 2


Factors are important when you are doing classification or regression in R using categorical variables. Try fitting a simple linear regression model (lm) with just a vector of strings. It is going to give you an error. Give it a shot with factors, and it will go through.

If you are looking for a more in-depth answer, please read the following link:


  • 1
    $\begingroup$ Your statement is false, R will convert a character vector for you. $\endgroup$
    – mdewey
    Commented Oct 11, 2016 at 17:39

Factors are variables, that have set and unchangeable (it is possible, but you shouldn't need to do it) values called levels. The corresponding variable then only holds a number corresponding to the index of the level instead of the actual string.

It is memory-wise much less expensive to hold a vector of integers that strings!!

Say you have a x=("hello", "name", "hello) you can convert it to a factor variable and you will have x = c(1,2,1), levels=c("hello", "name"). The more strings and longer you have the more memory you save.

Also from computational point of view, you cannot put strings in models, so it represents categorical variables, as pointed out by Ray


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