If you are clear on the pipe operator %>%
then two more pipes can help you save some typing and write more efficient code. However, neither are critical for this course. All of them require that you load the magrittr
package explicitly - it is installed as part of the tidyverse, but not loaded.
library(tidyverse) library(magrittr) #Example data constituencies <- read_csv(url("http://empower-training.de/Gold/ConstituencyData2019.csv"), col_types = "_cfddddfffddddfffdfdddd")
%$%
)Inside dplyr pipes, you do not need to use the $
to access variables within the dataframe. However, that does not work in some base-R functions such as cor.test()
. For them, %$%
can expose the variables in a dataframe temporarily (until the end of that command) so that they can be accessed as if they were separate variables in your environment.
#Normal code cor.test(constituencies$MedianAge, constituencies$ElectionConShare) #With the exposition pipe constituencies %$% cor.test(MedianAge, ElectionConShare)
Clearly in this case, the difference is slight but you might find it more readable as well. In other cases, this can spare you from having to save a filtered dataset or otherwise processed dataset into a new variable that you are only using once.
constituencies %>% filter(ContType == "County") %$% cor.test(MedianAge, ElectionConShare)
%<>%
)Quite often, we want to edit an element in place, which leads to some repetition as you need to specify that you want to put it into the pipe and then save it back in place.
#Normal code constituencies <- constituencies %>% filter(ConstituencyName != "Chorley") #With assignment pipe constituencies %<>% filter(ConstituencyName != "Chorley")
The assignment pipe here takes constituencies
, puts it into the pipeline, and takes the result at the end to save back into constituencies
. It can be particularly pleasant when you want to apply a function to a single variable, but be careful not to use it accidentally - if you type %<>%
instead of %>%
you will create bugs in your code that are not easy to spot.
constituencies$ElectionWon %<>% relevel(ref="Lab")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.