How to quickly load some sample data (in R)
Task
Sometimes you just need to try out a new piece of code, whether it be data manipulation, statistical computation, plotting, or whatever. And it’s handy to be able to quickly load some example data to work with. There is a lot of freely available sample data out there. What’s the easiest way to load it?
Solution
R comes with many datasets in its datasets
package.
Ensure that you have it installed as follows.
1
library(datasets)
Then you can load any one of them with the data
function, as follows.
1
2
data(iris) # Load the famous Fisher's irises dataset.
head(iris) # It has been placed in a variable of the same name.
1
2
3
4
5
6
7
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
To page through a list of all available datasets, just call data()
with no arguments.
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)