How to select row based columns using dplyr

I can select and rename the column name like this without a problem:


library(tidyverse)
iris <- as.tibble(iris)
iris %>% select(sepal_ln = Sepal.Length, sepal_wd = Sepal.Width)
#> # A tibble: 150 × 2
#>    sepal_ln sepal_wd
#>       <dbl>    <dbl>
#> 1       5.1      3.5
#> 2       4.9      3.0
#> 3       4.7      3.2
#> 4       4.6      3.1
#> 5       5.0      3.6
#> 6       5.4      3.9
#> 7       4.6      3.4
#> 8       5.0      3.4
#> 9       4.4      2.9
#> 10      4.9      3.1
#> # ... with 140 more rows

But I want me to do this in order to call a column from a row instead of a column name. I tried the following, but this failed:

> wanted <- "Sepal"
> iris %>% select(sepal_ln = !! paste0(wanted,".Length"), 
+                 sepal_wd = !! paste0(wanted,".Width"), 
+ )
Error: "Sepal.Length", "Sepal.Width": must resolve to integer column positions, not string
> 

What is the right way to do this?

+4
source share
1 answer

We can use select_

 iris %>% 
   select_(sepal_ln = paste0(wanted, ".Length"), paste0(wanted, ".Width"))

In addition, selectthere are wrappers to make it easier, i.e. one_of, contains, matchesEtc., to select the required columns of data

iris %>% 
  select(setNames(one_of(paste0(wanted, c(".Length", ".Width"))),
                 c("sepal_ln", "sepal_wd"))) %>%
  head(2)
# A tibble: 2 × 2
#   sepal_ln sepal_wd
#     <dbl>    <dbl>
#1      5.1      3.5
#2      4.9      3.0

NOTE. It is unclear whether the methods will select_become obsolete in the next version dplyr( 0.6.0) or not.

+3
source

Source: https://habr.com/ru/post/1675671/


All Articles