I’ve just realized that when I use write.table() for saving a data frame in R it does not save the order in which I had set the levels of a particular factor variable.
Checking the levels of Species in iris:
> levels(iris$Species)
[1] "setosa" "versicolor" "virginica"
Changing the order of the levels:
> iris$Species <- factor(iris$Species, levels=c("virginica","setosa","versicolor"))
> levels(iris$Species)
[1] "virginica" "setosa" "versicolor"
Saving the 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 new data frame:
> levels(newIris$Species)
[1] "setosa" "versicolor" "virginica"
How can I save the data frame so I can export it to other R sessions?
You probably want to use
saveandloadinstead.will save the R object itself to a file, and then you load it back into your workspace using
load. Don’t be confused whenloaddoesn’t return an object. It loads it into your workspace, so if you typels()you’ll see it listed.