How to preserve the order of levels in a data frame?

I just realized that when I use write.table()

to store a dataframe in R, it doesn't preserve the order in which I set the levels of a particular factorial variable.

Checking the levels of views in the iris:

> levels(iris$Species)
[1] "setosa"     "versicolor" "virginica" 

      

Changing the order of levels:

> iris$Species <- factor(iris$Species, levels=c("virginica","setosa","versicolor"))
> levels(iris$Species)
[1] "virginica"  "setosa"     "versicolor"

      

Saving a data frame and loading it into a new one:

> write.table(iris, 'iris_new.table')
> newIris <- read.table('iris_new.table')

      

Checking the order of the new data frame:

> levels(newIris$Species)
[1] "setosa"     "versicolor" "virginica"

      

How do I save a dataframe so that I can export it to other R sessions?

+3


source to share


1 answer


You might want to use save

and load

.

save(iris,file = "Iris.RData")

      



will save the R object itself to a file, and then you load it back into the workspace with load

. Don't be confused if it load

doesn't return an object. It loads it into your workspace, so if you type ls()

, you'll see it.

+6


source







All Articles