Pivots Part 1
In this JedR Trial we will explore your ability to pivot data to suit your needs. This is a common challenge to prepare data for charting in ggplot or Datawrapper.
Your droid editor (J-327D) has sent you some data they would like in a different format. J-327D is pretty sure you can use your JedR powers to “pivot” this data to their liking.
Make wider tables
This is the data you get from J-327D. It is a dataframe called characters
(as in characters in a story) that summarizes the starwars
data based on their species
and gender
identity.
But J-327D would like to see this data formatted so that it is easier to read … where each species is on its own row, with a column for each gender showing the number of characters. Like this:
Pivot to make more columns
Write the code below that will transform the characters
data into the format noted above.
characters |>
pivot_wider(names_from = gender, values_from = n)
|>
characters pivot_wider(names_from = gender, values_from = n)
You might review the pivoting vignette in the Tidyverse documentation.
Does it help to know which way you are going? Now you can just review the arguments of pivot_wider()
.
|>
characters pivot_wider(______from = gender, _______from = n)
Repeat, you must. Train yourself!
Well done, Padawan. Your droid editor is quite pleased, but now he wants to see the table with the species
as the new columns.
Can you take the characters
data that starts like this:
But make it look like this:
characters |>
pivot_wider(names_from = gender, values_from = n)
|>
characters pivot_wider(names_from = gender, values_from = n)
This is just like the challenge above in that you are still using pivot_wider()
, but you are using different values for the names and values.
Now let’s try going longer …
You’ve got the strength of a thousand stormtroopers (but with way better aim)!
Once you’ve completed the exercises above, move to the next part of this trial.