[This article was first published on R-Chart, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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)</b" world="">< !---data-->-data>
> write.csv(df, ‘df.csv’)
> df2< -read .csv="" b="" df.csv="">< !---read-->-read>
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:
http://simplystatistics.org/2015/07/24/stringsasfactors-an-unauthorized-biography/
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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.