Starting with data - exercise sheet
These exercises are partially derived from Software Carpentry teaching materials available under the CC BY 4.0 license:
https://swcarpentry.github.io/r-novice-gapminder/
https://swcarpentry.github.io/r-novice-inflammation/
https://datacarpentry.org/R-ecology-lesson/
★ marks the most important exercises. Focus on these if you are
running short on time.
Optional marks more challenging exercises. Do these if
you have time and find the other exercises easy.
Block 1: downloading and importing data
Lecture materials: Starting with data
Learning goals: import a spreadsheet of data in CSV format into R
This exercise block repeats the lecture contents - at this point it’s important that we’re all on the same page! We will need these data as we move on.
1.1 ★ Import some example data
(/home/rstudio/shared/portal_data_joined.csv) into an
object called surveys. You can use head() to
check that everything got imported correctly.
1.2 ★ We just imported data from outside our
current working directory. Let’s also try something inside the working
directory - create a new folder called testfolder (Files
pane on the bottom right –> New folder).
Block 2: inspecting data frames
Lecture materials: Starting with data
Learning goals: use functions to determine the properties of a data frame
2.1 ★ Inspect the surveys data
set using the following functions. We don’t need to memorize them now,
but eventually this can be useful when you are working with your own
data.
- Size:
dim()- returns a vector with the number of rows in the first element, and the number of columns as the second element (the dimensions of the object)nrow()- number of rowsncol()- number of columns
- Content:
head()- first 6 rowstail()- last 6 rows
- Names:
names()- column names (synonym ofcolnames()fordata.frameobjects)rownames()- row names
- Summary:
str()- structure of the object and information about the class, length and content of each columnsummary()- summary statistics for each column
2.2 ★ Based on the output of
str(surveys), can you answer the following questions?
- What is the class of the object
surveys? - How many rows and how many columns are in this object?
OPTIONAL Block 3: indexing and subsetting data frames
Lecture materials: Starting with data → section 5
Learning goals: use square brackets
([rows, columns]) and ranges of rows/columns
(e.g. 1:5) for selecting specific rows and columns of a
data frame
3.1 Create a data.frame
(surveys_200) containing only the data in row 200 of the
surveys dataset.
3.2 Notice how nrow() gave you the
number of rows in a data.frame?
- Use that number to pull out just that last row in the data frame.
- Compare that with what you see as the last row using
tail()to make sure it’s meeting expectations. - Pull out that last row using
nrow()instead of the row number. - Create a new data frame (
surveys_last) from that last row.
3.3 Use nrow() to extract the row that
is in the middle of the data frame. Store the content of this row in an
object named surveys_middle.
3.4 A trickier example: combine nrow()
with the - notation to exclude an index
(e.g. surveys[, -1]) to reproduce the behavior of
head(surveys), keeping just the first through 6th rows of
the surveys dataset. Don’t worry if you can’t get this one right!
Block 4: factors
Lecture materials: Starting with data → sections 6-8
Learning goals:
- convert a character variable into a factor with and rename and
reorder the levels of a factor with
factor()andlevels() - use
$to define a column in a data frame and square brackets[n]to define a value in a vector
4.1 ★ First assign the gender data from
surveys to a new object and convert it to a factor. You
probably also remember there are some measurements where the gender
information is either missing or undetermined, let’s call those
“undetermined”.
4.2 ★ Rename “F” and “M” to “female” and “male”, respectively.
4.3 ★ Can you reorder the data so that the
levels are ordered like this: undetermined,
male, female? After this, use
plot() to check how the data now look.
OPTIONAL Block 5: more on data frames
Learning goals: learn to spot problems with data types when importing data frames into R
5.1 We have seen how data frames are created when
using read.csv(), but they can also be created by hand with
the data.frame() function. There are a few mistakes in this
hand-crafted data.frame. Can you spot and fix them? Don’t
hesitate to experiment!
animal_data <- data.frame(
animal = c(dog, cat, sea cucumber, sea urchin),
feel = c("furry", "squishy", "spiny"),
weight = c(45, 8 1.1, 0.8)
)5.2 Can you predict the class for each of the
columns in the following example? Check your guesses using
str(country_climate):
- Are they what you expected? Why? Why not?
- What would you need to change to ensure that each column had the accurate data type?
country_climate <- data.frame(
country = c("Canada", "Panama", "South Africa", "Australia"),
climate = c("cold", "hot", "temperate", "hot/temperate"),
temperature = c(10, 30, 18, "15"),
northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"),
has_kangaroo = c(FALSE, FALSE, FALSE, 1)
)Block 6: arguments for CSV importing
Lecture materials: Importing and exporting data
Learning goals: use arguments with
read.csv() to avoid common problems when reading in
spreadsheet data into R
6.1 ★ Import a new data set on car speeds
(/home/rstudio/shared/car-speeds.csv) and assign it to an
object called carSpeeds.
6.2 ★ Have a look at the structure of
carSpeeds using str(). Then try re-importing
the data with the header argument set to false:
header = FALSE. How does the new data set differ from the
previous one?
6.3 The car colour labels contain accidental whitespaces. You can see this by running:
unique(carSpeeds$Color)
# Note that here we are referring to a specific column in a data frame with `dataframe$column`To fix the problem with whitespaces, try importing the data using the
strip.white argument:
strip.white = TRUE, sep = ","
The strip.white argument must be accompanied by the
sep argument, by which we indicate the type of delimiter in
the file (the comma for most .csv files). In other words, we need to add
sep = ',' to the import command.
Use unique() to check if it worked.
Block 7: exporting data and saving scripts
Lecture materials: Importing and exporting data
Learning goals:
- export a data frame from R into a CSV file
- use arguments to avoid common problems with
write.csv() - export data from the RStudio course environment to your own computer
The first two steps were covered in the lecture, so skip to step 7.3 if you already ran them.
7.1 ★ Create a new folder for output files,
called data_output.
7.2 ★ Export the car speeds data. The
write.csv() function requires a minimum of two arguments,
the data to be saved and the name of the output file. The output file
name should be in quotation marks (because it is a character string and
not an object in our R environment).
7.3 View the output file by clicking on on the file
name and select View (or read the data back into R with
read.csv() into a new object and inspect the object). It
should have three columns (Color, Speed, State). What is wrong?
7.4 Our read.csv() command above has
inserted an extra column of row names into the data frame. We can use
the argument row.names with write.csv to
control this. R’s default for this argument is TRUE, and
since it does not know what else to name the rows for the cars data set,
it resorts to using row numbers. To correct this, we can set
row.names to FALSE. Export your original
carSpeeds data again with write.csv and this time add
row.names = FALSE. View the file again to check if it
worked.
7.5 ★ Save your R script (File –> Save as…).
7.6 ★ Export your data from RStudio Server.
- Go to the "Files" pane (on the right, next to "Plots")
- Tick the empty boxes next to the files / folders you would like to export
- Click on "More" (look for a cogwheel symbol)
- Click on "Export". After this, specify a suitable name for the .zip file. The file will be saved into your default downloads folder.