R Oddities: Strings in DataFrames

July 29, 2015

(This article was first published on R-Chart, and kindly contributed to R-bloggers)

Have you ever read a file into R and then encountered strange problems filtering and sorting because the strings were converted to factors?  For instance, you might think the two data frames, df and df2 below are contain the same data

> df<-data .frame="" c="" hello="" stringsasfactors="FALSE)
write.csv(df, ‘df.csv’)
df2<-read .csv="" b="" df.csv="">

But look the dimensions are different

> dim(df)
[1] 1 1
> dim(df2)
[1] 1 2

And on further analysis – they are indeed different classes:

> class(df$V1)
[1] “character”
> class(df2$V1)
[1] “factor”

This behavior is very confusing to many when first introduced to R.  Over time, I accepted it but didn’t really understand how or why it originated.   Roger Peng over at the Simply Statistics blog has a great write up on why R operates this way:


To leave a comment for the author, please follow the link and comment on their blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)