This is problem set #2, in which we hope you will practice the packages tidyr and dplyr. Along with the tutorial we used in class, there are some great cheat sheets from RStudio.
This data set comes from a replication of Janiszewski and Uy (2008), who investigated whether the precision of the anchor for a price influences the amount of adjustment. (We use these data briefly in the tutorial).
In the data frame, the Input.condition variable represents the experimental condition (under the rounded anchor, the rounded anchor, over the rounded anchor). Input.price1, Input.price2, and Input.price3 are the anchors for the Answer.dog_cost, Answer.plasma_cost, and Answer.sushi_cost items.
Load the tidyverse package and the data
library(tidyverse)
## Loading tidyverse: ggplot2
## Loading tidyverse: tibble
## Loading tidyverse: tidyr
## Loading tidyverse: readr
## Loading tidyverse: purrr
## Loading tidyverse: dplyr
## Conflicts with tidy packages ----------------------------------------------
## filter(): dplyr, stats
## lag(): dplyr, stats
library(ggthemes)
d <- read.csv("data/janiszewski_rep_cleaned.csv")
This data frame is in wide format - that means that each row is a participant and there are multiple observations per participant. This data is not tidy.
To make this data tidy, we’ll do some cleanup. First, remove the columns you don’t need, using the verb select.
HINT: ?select and the examples of helper functions will help you be efficient.
d.tidy <- d %>%
select(WorkerId,Input.condition,starts_with("Answer"))
# View(d.tidy) # Check
#Assumption: we don't care about input price so not selecting; just selecting answer
Try renaming some variables using rename. A good naming scheme is:
Try using the %>% operator as well. So you will be “piping” d %>% rename(...).
d.tidy <- d.tidy %>%
rename(workerid = WorkerId,
condition = Input.condition,
dog = Answer.dog_cost,
plasma = Answer.plasma_cost,
sushi = Answer.sushi_cost)
OK, now for the tricky part. Use the verb gather to turn this into a tidy data frame.
HINT: look for online examples!
d.tidy <- d.tidy %>%
gather(stimulus, answer, dog, plasma, sushi) #stimulus is the item name and answer is the value
Now spread these data back into a wide format data frame.
d.wide <- d.tidy %>%
spread(stimulus,answer)
NOTE: If you generally use plyr package, note that they do not play nicely together so things like the rename function won’t work unless you load dplyr after plyr.
As we said in class, a good thing to do is always to check histograms of the response variable. Do that now, using either regular base graphics (hist) or ggplot. What can you conclude?
d.tidy %>%
ggplot(aes(x = answer, col = stimulus)) +
stat_bin(bins = 50) # changed bin width; don't need a +
## Warning: Removed 1 rows containing non-finite values (stat_bin).
geom_histogram()
## geom_bar: na.rm = FALSE
## stat_bin: binwidth = NULL, bins = NULL, na.rm = FALSE, pad = FALSE
## position_stack
#We can conclude that each of the stimuli have distinct answer prices. It is hard to tell if there is a normal distribution for sushi (as the prices are so much lower), but dog and plasma seem to have skewed distributions.
OK, now we turn to the actual data anlysis. We’ll be using dplyr verbs to filter, group,mutate, and summarise the data.
Start by using summarise to compute the grand mean bet. (Note that this is the same as taking the grant mean - the value will come later. Right now we’re just learning the syntax of that verb.)
d.tidy %>%
summarise (mean = mean(answer, na.rm=TRUE)) #the bet is the answer, because this is what participants added; need to exclude missing answers
## mean
## 1 2022.557
This is a great time to get comfortable with the %>% operator. In brief, %>% allows you to pipe data from one function to another. So if you would have written:
d <- function(d, other_stuff)
you can now write:
d <- d %>% function(other_stufF)
That doesn’t seem like much, but it’s cool when you can replace:
d <- function1(d, other_stuff) d <- function2(d, lots_of_other_stuff, more_stuff) d <- function3(d, yet_more_stuff)
with
d <- d %>% function1(other_stuff) %>% function2(lots_of_other_stuff, more_stuff) %>% function3(yet_more_stuff)
In other words, you get to make a clean list of the things you want to do and chain them together without a lot of intermediate assignments.
Let’s use that capacity to combine summarise with group_by, which allows us to break up our summary into groups. Try grouping by item and condition and taking means using summarise, chaining these two verbs with %>%.
#By condition
d.tidy %>%
group_by(condition) %>%
summarise(mean = mean(answer,na.rm = TRUE), sd = sd(answer, na.rm = TRUE)) #need to exclude blank values
## # A tibble: 3 x 3
## condition mean sd
## <fctr> <dbl> <dbl>
## 1 over 2092.139 1840.944
## 2 rounded 1994.698 1773.192
## 3 under 1977.688 1721.464
#By condition & stimulus
d.tidy %>%
group_by(condition, stimulus) %>%
summarise(mean = mean(answer,na.rm = TRUE), sd = sd(answer, na.rm = TRUE))
## # A tibble: 9 x 4
## # Groups: condition [?]
## condition stimulus mean sd
## <fctr> <chr> <dbl> <dbl>
## 1 over dog 1898.300000 419.7275101
## 2 over plasma 4300.333000 826.1351787
## 3 over sushi 8.322414 0.6082155
## 4 rounded dog 1884.482414 476.2391705
## 5 rounded plasma 4091.655172 880.5919793
## 6 rounded sushi 7.955517 0.6004022
## 7 under dog 1906.964286 406.8030265
## 8 under plasma 4018.357143 772.1201314
## 9 under sushi 7.742500 0.3769824
Are there condition differences?
Brief narrative answer here. The “over” condition has a higher mean than “rounded” and “under”. This makes sense becuase the “over” condition had higher anchor prices. What we need to figure out is the adjustment relative to the anchor (e.g. answer - anchor). In addition, the higher overall mean is for the sushi and plasma stimuli; for dog, under has a higher mean. This is interesting given under had a lower anchor price. This might lead us to wonder whether there is an interaction of conditon by stimulus.
How are we going to plot condition differences? They are fundamentally different magnitudes from one another. Really we need the size of the deviation from the anchor, which means we need the anchor value. Let’s go back to the data and add that in.
Take a look at these two complex piped expression.s You don’t have to modify it, but see what is being done here with gather, separate and spread. Run each part (e.g. the first verb, the first two verbs, etc.) and after doing each, look at head(d.tidy) to see what they do.
# clean up
d.tidy <- d %>%
select(WorkerId, Input.condition,
starts_with("Answer"),
starts_with("Input")) %>%
rename(workerid = WorkerId,
condition = Input.condition,
plasma_anchor = Input.price1,
dog_anchor = Input.price2,
sushi_anchor = Input.price3,
dog_cost = Answer.dog_cost,
plasma_cost = Answer.plasma_cost,
sushi_cost = Answer.sushi_cost)
# now do the gathering and spreading
d.tidy <- d.tidy %>%
gather(name, cost,
dog_anchor, plasma_anchor, sushi_anchor,
dog_cost, plasma_cost, sushi_cost) %>% #gathers both the anchor and cost variables all at once
separate(name, c("item", "type"), "_") %>% #creates two columns item & type from column name, separating by the "_" sign
spread(type, cost) #spreads item type (e.g. anchor or cost) and puts the cost value
Now we can do the same thing as before but look at the relative difference between anchor and estimate. Let’s do this two ways:
To do the first, use the mutate verb to add a percent change column, then comute the same summary as before.
pcts <- d.tidy %>%
mutate(pct_change = (abs(100*((cost - anchor)/anchor)))) %>%
group_by(condition, item) %>%
summarise(mean_pct_change = mean(pct_change, na.rm = TRUE))
To do the second, you will need to group once by item, then to ungroup and do the same thing as before. NOTE: you can use group_by(…, add=FALSE) to set new grouping levels, also.
HINT: scale(x) returns a complicated data structure that doesn’t play nicely with dplyr. try scale(x)[,1] to get what you need.
zscore <- d.tidy %>%
mutate(pct_change = (abs(100*((cost - anchor)/anchor)))) %>%
group_by(item) %>%
mutate(z.score = scale(pct_change, center = TRUE, scale = TRUE)[,1]) %>% #scale by pct_change; center = TRUE, scale = TRUE is the default so don't need to add
group_by(condition, item, add = FALSE) %>% #add = FALSe to override other grouping items
summarise(mean_z_score = mean(z.score, na.rm = TRUE))
OK, now here comes the end: we’re going to plot the differences and see if anything happened. First the percent change:
#Qplot Original -- Since stat & position have been 'deprecated' (e.g. they should be avoided); Thus going to use ggplot
#qplot(item, pct_change, fill=condition,
# position="dodge",
# stat="identity", geom="bar",
# data=pcts)
#GGPlot
pcts %>%
ggplot(aes(x = item, y = mean_pct_change, col = condition)) + #need to use mean_pct_change
geom_bar(stat="identity", position = "dodge") #dodge moves horizontally so not stacked; use stat = "identity" so that geom_bar uses values, rather than count (the default); see here: https://stackoverflow.com/questions/39679057/r-ggplot2-stat-count-must-not-be-used-with-a-y-aesthetic-error-in-bar-graph/39679104
and the \(z\)-scores:
#qplot(item, z, fill=condition,
# position="dodge",
# stat="identity", geom="bar",
# data=z.scores)
#GGPlot
zscore %>%
ggplot(aes(x = item, y = mean_z_score, col = condition)) +
geom_bar(stat="identity", position = "dodge")
What do you you see in this replication?
Brief narrative answer here. The original paper (experiment 1) found that “the rounded anchors … resulted in an adjustment that was larger than the average adjustment observed with the precise anchors … the estimates did not differ between precise under and precise over anchors” (p.122). This analysis was done across various items, including a plasma tv. In our replication, it seems that rounded resulted in a larger adjustment for dog & sushi, but not for plasma. Moreover, it seems that over and under differed for the plasma tv (and potentially for the other two stimuli based on the z score chart). Thus, it seems that there was something strange with the plasma TV stimulus as the expected results did not hold (with the caveat we haven’t done any statistical analyses). However, the intended results (rounded is higher; over and under around the same) seemed to hold for the dog and sushi stimuli.