concept dplyr in category R

appears as: dplyr, dplyr, dplyr, The dplyr
R in Action, Third Edition

This is an excerpt from Manning's book R in Action, Third Edition.

One set of packages, collectively called the tidyverse, deserves particular attention. This is a relatively new collection of packages that offers a streamlined, consistent, and intuitive approach to data manipulation and analysis. The advantages offered by tidyverse packages (with names like tidyr, dplyr, lubridate, stringr and ggplot2) is changing the way data scientists write code in R, and we will be employing these packages often. In fact, the opportunity to describe how to use these packages for data analysis and visualization was a major motivation for writing a third edition of this book!

This time we'll use dplyr functions to manipulate the dataset. The code is provided in listing 3.7. Since dplyr is not part of base R, install it (install.packages("dplyr")) before first use.

Listing 3.7 Manipulating data with dplyr
manager <- c(1, 2, 3, 4, 5)
date <- c("10/24/08", "10/28/08", "10/1/08", "10/12/08", "5/1/09")
country <- c("US", "US", "UK", "UK", "UK")
gender <- c("M", "F", "F", "M", "F")
age <- c(32, 45, 25, 39, 99)
q1 <- c(5, 3, 3, 3, 2)
q2 <- c(4, 5, 5, 3, 2)
q3 <- c(5, 2, 5, 4, 1)
q4 <- c(5, 5, 5, NA, 2)
q5 <- c(5, 5, 2, NA, 1)
leadership <- data.frame(manager, date, country, gender, age,
                         q1, q2, q3, q4, q5, stringsAsFactors=FALSE)
 
library(dplyr)                                                  #A
 
leadership <- mutate(leadership,                                #B
                     total_score = q1 + q2 + q3 + q4 + q5,      #B
                     mean_score = total_score / 5)              #B
 
leadership$gender <- recode(leadership$gender,                  #C
                            "M" = "male", "F" = "female")       #C
 
leadership <- rename(leadership, ID = "manager", sex = "gender")#D
 
leadership <- arrange(leadership, sex, total_score)             #E
 
leadership_ratings <- select(leadership, ID, mean_score)        #F
 
leadership_men_high <- filter(leadership,                       #G
                              sex == "male" & total_score > 10) #G

First the dplyr package is loaded #A. Then mutate() function is used to create a total score and mean score #B. The format is

dataframe <- mutate(dataframe,
                    newvar1 = expression,
                    newvar2 = expression, ...).

Note that when using dplyr, you don't place quote marks around variable names. The new variables are added to the data frame.

Exploring Data with R

This is an excerpt from Manning's book Exploring Data with R.

The edr package will give us the dataset needed for the examples in this chapter: sw.  This dataset is a modified version of the starwars dataset that is available in the dplyr package. Whenever we load in the edr package using library(edr), the sw table will be available for use. This particular dataset has 87 rows, one for each Star Wars character, and the following 8 variables (or columns):

Figure 3.22. Modifying data with dplyr; plotting it with ggplot.
Listing 4.2. How to make data pivot_longer() and thus make it more tidy.
```{r winni_pivot_longer, paged.print=FALSE}
winni_mod <-
  winniweather %>%                    #A
  pivot_longer(
    starts_with("temp"),              #B
    names_to = "hour",                #C
    values_to = "temp"                #D
  )
 
winni_mod
```
# A We are piping the winniweather dataset to the pivot_longer() function.
# B We start by supplying a set of columns that contain data to be put in a ‘longer’ format (i.e., one observation per row). The starts_with() function is familiar: it’s also used in dplyr’s select() function.
# C The names_to argument expects a name for a new column. This new column will contain the column names from the starts_with() selection.
# D The values_to argument also expects a name (again, of your choosing) for a new column; this column will contain the values.
Practical Data Science with R, Second Edition

This is an excerpt from Manning's book Practical Data Science with R, Second Edition.

We have now performed a few standard data analysis steps: loading the data, reprocessing a few columns, and taking a look at the data. These steps have been performed using what we call “base R,” which means using features and functions coming from the R language itself and the basic packages that are automatically attached (such as base, stats, and utils). R is well suited to data processing tasks, as this is what most users come to R to do. There are extension packages such as dplyr that have their own data processing notation and can perform many steps directly against data in a database in addition to being able to work on data held in memory. We share examples showing how to perform the same data processing steps using base R in the R Markdown example PDSwR2/PUMS/PUMS1.Rmd, or using dplyr in PDSwR2/PUMS/PUMS1_dplyr.Rmd, or using the advanced query generation package rquery in PDSwR2/PUMS/PUMS1_rquery.Rmd.

  • dplyr— dplyr is a popular data manipulation package that emphasizes data manipulations through sequences of SQL-like (or Codd-style) operators. dplyr is usually not as fast (or space efficient) as data.table, but the notations are convenient.
  • Beyond Spreadsheets with R

    This is an excerpt from Manning's book Beyond Spreadsheets with R.

    Then try to use the dplyr package, which also contains a count() function (with a much more useful implementation):

    # install.packages("dplyr")
    library(dplyr)
    #
    #> Attaching package: 'dplyr'
    #  The following object is masked _by_ '.GlobalEnv':
    #>
    #>     count
    #  The following objects are masked from 'package:stats':
    #>
    #>     filter, lag
    #  The following objects are masked from 'package:base':
    #>
    #>     intersect, setdiff, setequal, union

    The count() function takes precedence because it is in the global environment (The following object is masked by '.GlobalEnv': count). Some other functions are masked from other packages because dplyr is now higher on the search path (the more recently a package is loaded and attached, the higher its precedence).

    The dplyr (“dee-ply-er”) package by Hadley Wickham makes working with data.frames as simple as possible through a consistent and well-thought-out set of verbs (see figure 6.3).

    Figure 6.3 dplyr verb construction

    verb.png

    dplyr is at the top of my list of recommended add-on packages for R. I start every session with it loaded because I’m certain I’m going to use it. It provides a consistent interface of verbs for manipulating tidy data — data that is formatted in a proper, regulated manner, with one row per observation and one column per quantity. This is the structure of a data.frame, hence the d in dplyr. The functions in this package take one or more data.frames and produce modified copies of it/them with rows and/or columns selected, added, removed, or altered in some way.

    head(    #1  
      dplyr::mutate(
        mtcars,    #2  
        hp_per_cc_auto = ifelse(am, hp / disp, NA)    #3  
      )  #4  
    )
    
    #>    mpg cyl disp  hp drat    wt  qsec vs am gear carb hp_per_cc_auto
    #> 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4      0.6875000
    #> 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4      0.6875000
    #> 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1      0.8611111
    #> 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1             NA
    #> 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2             NA
    #> 6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1             NA
    
    #1   Only print() the first six rows.
    #2   Modifies the mtcars data.frame using dplyr
    #3   Creates a new column hp_per_cc_auto, referencing columns from mtcars using nonstandard evaluation
    #4   Uses am (does the vehicle have an automatic transmission?) as the test; 1 indicates TRUE and is coercible. Where the test value is TRUE, divides hp by disp; otherwise returns NA.