Section 4.3 Creating a Sample Dataset
There are many different ways to get data into R. The most common are:
-
Loading an excel file or CSV
-
Calling data into R using an API
-
Loading data from a particular package (see chapter 7)
What happens if you do not have data to insert into R? What if you want to create your own data in R to run analyses, merge, and graph?
R makes it very simple to do exactly that! Using the automatically installed command
data.frame R makes it possible to make your very own data frame with whatever you want inside. Here, we are going to create two datasets:
-
mets: This is going to be a data frame with 10 rows, each row being a different game, and the number of runs scored by the Mets in that game.
-
yankees: This is going to be a data frame with 10 rows, each row being a different game, and the number of runs scored by the Yankees in that game.
In this scenario, we can imagine that for whatever reason, we are unable or do not want to upload any data to R, but instead, create the data for ourselves. We will create our tables using 2025 Major League Baseball (MLB) data, and will have two columns:
-
Game: A number representing which game it is.
-
Score: The total runs the respective team scored in that game.
To summarize, we will be taking the scores from the first 10 Yankees games and the first 10 Mets games and creating a data frame with our data, and utilizing similar techniques introduced in SubsectionΒ 1.6.1.
mets <- data.frame(
Game = c(1,2,3,4,5,6,7,8,9,10),
Mets_Score = c(4,20,12,5,3,9,9,10,4,2)) # This is where we manually put our numbers in
head(mets) # This calls the first 6 rows of the data
Game Mets_Score 1 1 4 2 2 20 3 3 12 4 4 5 5 5 3 6 6 9
yankees <- data.frame(
Game = c(1:10), # The colon tells R "any number between 1 and 10."
Yankees_Score = c(3,8,2,3,2,6,5,3,2,7))
tail(yankees) # This calls the last 6 rows of the data
Game Yankees_Score 5 5 2 6 6 6 7 7 5 8 8 3 9 9 2 10 10 7
Perfect! We created two different data frames, mets and yankees with each having the two columns we were looking for.
To get more practice, letβs do it again, but instead, we will do it with the next ten games of the 2025 season.
mets_second_ten <- data.frame(
Game = c(11:20),
Mets_Score = c(10,0,7,1,8,5,3,3,4,1))
yankees_second_ten <- data.frame(
Game = c(11:20),
Yankees_Score = c(0,4,1,8,4,4,4,4,6,1))
Now, we successfully have datasets for the first 10 and first 20 games of the 2025 MLB season for both the Mets and the Yankees.
