Avoid rbind()/cbind() conversion from numeric to factor

I want to put @mtelesha 's comment to the front.

Use stringsAsFactors = FALSE in cbind or cbind.data.frame:

x <- data.frame(a = letters[1:5], b = 1:5)
y <- cbind(x, c = LETTERS[1:5])
class(y$c)
## "factor"
y <- cbind.data.frame(x, c = LETTERS[1:5])
class(y$c)
## "factor"
y <- cbind(x, c = LETTERS[1:5], stringsAsFactors = FALSE)
class(y$c)
## "character"
y <- cbind.data.frame(x, c = LETTERS[1:5], stringsAsFactors = FALSE)
class(y$c)
## "character"

UPDATE (May 5, 2020):

As of R version 4.0.0, R uses a stringsAsFactors = FALSE default in calls to data.frame() and read.table().

https://developer.r-project.org/Blog/public/2020/02/16/stringsasfactors/


You can use rbind.data.frame and cbind.data.frame instead of rbind and cbind.

Tags:

R