Gluing data frames
Data is very often stored in data frames. Most of the time, we want to create an analysis that is also readable for humans. For example, it could be valuable to print a sentence about the size of our data frames. By combining glue()
with nrow()
and ncol()
, we can return values and create a sentence that reports on the dimensions of our data frames.
Luckily, the glue
package is part of the tidyverse
package collection and was built with data frames in mind, so we can operate on entire data frame columns. We can, for example, use it inside mutate()
to create a new column with a concatenated string that contains values of other columns. In this exercise, you will apply these examples on the users
data frame which contains values of other columns.
This exercise is part of the course
Intermediate Regular Expressions in R
Exercise instructions
- Use the
glue()
function to report the number of rows and columnsusers
has, by storing them in then
andm
temporary variables respectively. - Inspect the data frame
users
by just executing the line that prints the column names. - Mutate users to create a new column
n_logins
which reports the number of times users logged in by using thename
andlogins
columns respectively.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create two temporary variables "n" and "m" and use them
glue(
"The data frame 'users' has ___ rows and ___ columns.",
___ = nrow(users),
___ = ncol(users)
)
# This lists the column names of the data frame users
colnames(users)
# Use them to create a sentence about the numbers of logins
users %>% mutate(
n_logins = glue("___ logged in ___ times.")
)