There is very little new material needed for this lab. You may need
to refer back to last week’s Strings lab as necessary. Feel
free! Questions 1 and 2 should be doable, but not necessarily
straight-forward. Question 3 introduces just a bit of dplyr
applicability to the stringr and lubridate
stuff.
library(dplyr)
library(stringr)
library(lubridate)
library(ggplot2)
dplyrSo far, we have primarily used functions from stringr to
examine or modify individual character strings. However, these functions
can also be used within dplyr to create new variables and
summarize information across groups.
Consider a small dataset containing customer reviews for three different products:
reviews = data.frame(
Product = c("Laptop", "Laptop", "Laptop", "Laptop",
"Headphones", "Headphones", "Headphones", "Headphones",
"Keyboard", "Keyboard", "Keyboard", "Keyboard"),
Review = c("Great laptop, great battery life",
"Good performance but expensive",
"Battery life is terrible",
"Great value for the price",
"Excellent sound quality",
"Great sound but poor battery life",
"Terrible fit and poor comfort",
"Good headphones for the price",
"Great keyboard and excellent keys",
"Poor build quality",
"Good value, great typing experience",
"Terrible keyboard, poor quality")
)
Suppose we want to identify reviews containing positive words such as
"great", "good", or "excellent".
We can use str_detect() inside mutate() to
create a new logical variable:
reviews |>
mutate(Positive = str_detect(Review,
regex("great|good|excellent",
ignore_case = TRUE)))
## Product Review Positive
## 1 Laptop Great laptop, great battery life TRUE
## 2 Laptop Good performance but expensive TRUE
## 3 Laptop Battery life is terrible FALSE
## 4 Laptop Great value for the price TRUE
## 5 Headphones Excellent sound quality TRUE
## 6 Headphones Great sound but poor battery life TRUE
## 7 Headphones Terrible fit and poor comfort FALSE
## 8 Headphones Good headphones for the price TRUE
## 9 Keyboard Great keyboard and excellent keys TRUE
## 10 Keyboard Poor build quality FALSE
## 11 Keyboard Good value, great typing experience TRUE
## 12 Keyboard Terrible keyboard, poor quality FALSE
Recall that the | character in a regular expression
allows us to match any of several alternatives. The regex()
function allows us to ignore differences in capitalization.
The new Positive variable is TRUE whenever
a review contains at least one of these words and FALSE
otherwise.
We can also combine str_detect() with
group_by() and summarize() to count the number
of reviews containing these words for each product:
reviews |>
group_by(Product) |>
summarize(PositiveReviews = sum(str_detect(
Review, regex("great|good|excellent", ignore_case = TRUE)
)))
## # A tibble: 3 × 2
## Product PositiveReviews
## <chr> <int>
## 1 Headphones 3
## 2 Keyboard 2
## 3 Laptop 3
Remember that R treats TRUE as 1 and FALSE
as 0 when calculating sums. Consequently,
sum(str_detect(...)) counts the number of reviews
containing at least one match within each group.
Similarly, taking the mean of a logical variable
gives us the proportion of observations for which the condition is
TRUE.
Using the reviews dataset, answer the following
questions.
Part A: Create a new variable called
Negative that identifies reviews containing either
"poor" or "terrible". Use this variable to
filter the dataset to contain only negative reviews. Display
the resulting dataset.
Part B: Using group_by() and
summarize(), calculate the number of reviews containing
either "poor" or "terrible" for each
product.
Part C: Calculate the proportion of reviews
containing either "poor" or "terrible" for
each product. Which product has the highest proportion of negative
reviews according to this definition? (Do not use your filtered dataset
from Part A for this calculation)
The data below comes from a real driving simulator experiment. The “disposition” file records the experimental participants, their assigned conditions, and the driving simulator output files that record a time-series of driver/vehicle inputs in a particular simulated drive. Output from the simulator are stored as DAQ file.
disp = read.csv("https://NFriedrichsen.github.io/data/disposition.csv")
head(disp)
## Analyze Reduced Ignore Discard DaqPath
## 1 X NA Control\\C_001_POST
## 2 X NA Control\\C_002__PRE
## 3 X NA Control\\C_003__PRE
## 4 X NA Occasional\\O_001__PRE
## 5 X NA Control\\C_004_POST
## 6 X NA Frequent\\F_001__PRE
## DaqName Date
## 1 1_RuralRedLight_20180905113244.daq 9/5/2018 23:01
## 2 3_RuralRedLight_20180912092144.daq 9/12/2018 23:11
## 3 2_RuralRedLight_20180914094223.daq 9/14/2018 23:12
## 4 1_RuralRedLight_20180917093224.daq 9/17/2018 23:10
## 5 3_RuralRedLight_20180928135832.daq 9/28/2018 23:04
## 6 4_RuralRedLight_20181003103829.daq 10/3/2018 23:11
Exclude any drives that do not have an “X” in the reduced column.
Then, using stringr functions as appropriate, process the
information recorded in “disposition.csv” into a data frame with the
following columns:
Hints:
\\\\ is needed to match a
single \_[^\\d]*$ useful. Think
about what it will will match.data.frame to assemble them into a data frame.Printed below are the first 10 rows of the target data.frame in the requested format.
## Group SubjectID Treatment Scenario DriveNumber
## 1 Control C_001 POST RuralRedLight 1
## 2 Control C_002 PRE RuralRedLight 3
## 3 Control C_003 PRE RuralRedLight 2
## 4 Occasional O_001 PRE RuralRedLight 1
## 5 Control C_004 POST RuralRedLight 3
## 6 Frequent F_001 PRE RuralRedLight 4
## 7 Frequent F_002 PRE RuralRedLight 4
## 8 Control C_005 POST RuralRedLight 3
## 9 Frequent F_003 PRE RuralRedLight 4
## 10 Occasional O_002 PRE RuralRedLight 1
\(~\)
The 2015 Boston Marathon took place on April 20th, 2015. It was the 119th running of one of the world’s most well-known races. The data below contain information, results, and splits for each finisher:
marathon = read.csv("https://NFriedrichsen.github.io/data/BostonMarathon2015.csv")
The marathon data record running times as character strings in hours,
minutes, and seconds. The hms() function from
lubridate can convert these strings into time durations,
which can then be used in calculations.
For example:
time1 = hms("1:25:30")
time2 = hms("2:10:15")
time2 - time1
## [1] "1H -15M -15S"
seconds(time1)
## [1] "5130S"
The seconds() function converts a duration into a
numerical quantity measured in seconds. This will be useful when
calculating running paces.
Part A: A marathon is approximately 26.2 miles, making the first half 13.1 miles. Using this information, calculate the per mile pace (in seconds) for each participant in the first half of the race. Be sure to store your results.
Part B: Now calculate the pace per mile in the second half of the race. Be sure to store your results.
Part C: Challenge Question (Not
required, but I’ll think you’re cool if you can do it!) Now create a
scatterplot displaying the relationship between pace per mile in the
first half of the race vs. pace per mile in the second half of the race
by age and sex. To facilitate this, you should assemble your results
from Parts A and B into a data frame that also includes the “Age” and
“M.F” columns from the original data. A target graphic is given below.
Note: scale_x_time() and
scale_y_time() can be used to display your first half and
second half paces on a time scale. The graph shown below uses the
argument alpha = 0.2 to reduce the impact of over-plotting,
and a 45-degree line is added using geom_abline().