Take the 2-minute tour ×

I just noticed this. I have a big DF with a mix of integer, character and strings columns. later I need to order the DF by a numeric column.

The original columns are of the respective type, but when I combine them into the DF all the columns changes to factor and the column I need for the sort as well, so the sorit gives something like 1, 10, 100, etc . instead of 1, 2, 3.

Here is just an example of my problem.

a <- 1:10
b <- c(1,3,5,6,2,10,100,110,7,4)
c <- LETTERS[1:10]
d <- as.data.frame(cbind(a, b, c))  # I am using this construction
e <- d[with(d, order(b)), ]

Any idea on how to "fix" this?
Am I doing something wrong?

Thanks for your time,

share|improve this question
try d <- data.frame(a, b, c) –  kohske Jun 7 '12 at 2:11
I just found that form and tested. It works!. Post your comment as answer and Ill accept it. Thanks –  notuo Jun 7 '12 at 2:14
Where are people getting the notion that they should be using the data.frame(cbind(...)) construction ???!!!??? It is going to coerce all the vectors to character if there is a single character vector in the arguments (and as @TimP and kohske point out then it's going to turn them into factors.) There is an options() setting to change the default of stringsAsFactors to FALSE. –  IShouldBuyABoat Jun 7 '12 at 4:17
@DWin - Useful point about the option, but my preference is to be defensive and add the stringsAsFactors argument explicitly... it's way too easy for someone else to accidentally run the code (or a fragment of it) with the option not enabled correctly, and the time it takes to diagnose and fix the problem usually dwarfs the few seconds required to just add those few characters! :) –  Tim P Jun 7 '12 at 5:50
@DWin i don't know where everyone else gets it, but I absorbed by osmosis while learning R, and had to fight rather hard to get rid of it afterwards. –  richiemorrisroe Jun 7 '12 at 8:20
show 1 more comment

1 Answer

up vote 0 down vote accepted

Actually you need to do:

d <- data.frame(a, b, c, stringsAsFactors=FALSE)

The last part stringsAsFactors=FALSE prevents column d$c from being converted to factors. Include it, and your strings will stay as strings.

Don't forget stringsAsFactors=FALSE - it will save you untold misery, trust me!

share|improve this answer
Thanks. I use stringsAsFactors in my read.table's but I forgot to use it here. Thanks to all. –  notuo Jun 7 '12 at 14:14
add comment

Your Answer


