The package ‘lplyr’ extends some dplyr verbs to lists and pairlists:
xs <- list(x1 = 1:3,
x2 = 2:5,
x3 = "alpha")
mutate(xs, x4 = 4) %>% str
rename(xs, x0 = x1) %>% str
Usual verbs made for standard evaluation work as well:
mutate_(xs, x4 = ~ 4) %>% str
#> List of 4
#> $ x1: int [1:3] 1 2 3
#> $ x2: int [1:4] 2 3 4 5
#> $ x3: chr "alpha"
#> $ x4: num 4
rename_(xs, x0 = ~ x1) %>% str
#> List of 3
#> $ x0: int [1:3] 1 2 3
#> $ x2: int [1:4] 2 3 4 5
#> $ x3: chr "alpha"
The mutate_which
and transmute_which
functions are made for adding new variables or modifying existing ones on a subset of the data.
df <- mtcars[1:6,]
mutate_which(df, gear==4, carb = 100)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 100
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 100
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 100
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
transmute_which(df, gear==4, carb = 100)
#> carb
#> Mazda RX4 100
#> Mazda RX4 Wag 100
#> Datsun 710 100
#> Hornet 4 Drive 1
#> Hornet Sportabout 2
#> Valiant 1
There is also a standard evaluation version of these functions, called mutate_which_
and transmute_which_
:
mutate_which_(df, ~ gear==4, carb = ~ 100)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 100
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 100
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 100
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
transmute_which_(df, ~ gear==4, carb = ~ 100)
#> carb
#> Mazda RX4 100
#> Mazda RX4 Wag 100
#> Datsun 710 100
#> Hornet 4 Drive 1
#> Hornet Sportabout 2
#> Valiant 1
The function pull
selects a column in a data frame and transforms it into a vector. This is useful to use it in combination with magrittr’s pipe operator and dplyr’s verbs.
df[["mpg"]]
#> [1] 21.0 21.0 22.8 21.4 18.7 18.1
df %>% pull(mpg)
#> [1] 21.0 21.0 22.8 21.4 18.7 18.1
# more convenient than (mtcars %>% filter(mpg > 20))[[3L]]
df %>%
filter(mpg > 20) %>%
pull(3)
#> [1] 160 160 108 258