简体   繁体   中英

How to select quoted columns with with vector as input using dplyr

I have the following data frame (tibble)

library(dplyr)

dat <- structure(list(`YY_164.XXX-ad` = c(0.004, 0, 0, 0.001, 0.001, 
0.001), `YY_165.XXX-ad` = c(0.022, 0.001, 0, 0.001, 0.002, 0
), `YY_162.XXX-ad` = c(0.013, 0, 0, 0.001, 0.001, 0.001), `YY_163.XXX-ad` = c(0.023, 
0, 0, 0.001, 0, 0.001), `YY_166.XXX-ad` = c(0.062, 0.001, 0.001, 
0.001, 0.005, 0.001)), .Names = c("YY_164.XXX-ad", "YY_165.XXX-ad", 
"YY_162.XXX-ad", "YY_163.XXX-ad", "YY_166.XXX-ad"), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))
dat
#> # A tibble: 6 x 5
#>   `YY_164.XXX-ad` `YY_165.XXX-ad` `YY_162.XXX-ad` `YY_163.XXX-ad`
#>             <dbl>           <dbl>           <dbl>           <dbl>
#> 1           0.004           0.022           0.013           0.023
#> 2           0.000           0.001           0.000           0.000
#> 3           0.000           0.000           0.000           0.000
#> 4           0.001           0.001           0.001           0.001
#> 5           0.001           0.002           0.001           0.000
#> 6           0.001           0.000           0.001           0.001
#> # ... with 1 more variables: `YY_166.XXX-ad` <dbl>

What I want to do is to select column based on a vector:

pp <- c('YY_164.XXX-ad','YY_165.XXX-ad')

I tried this but with error:

dat %>% 
  select_(pp)
#> Error in overscope_eval_next(overscope, expr): object 'YY_164.XXX' not found

What's the right way to do it?

What's wrong with select ? Did you try it? Have you got a different version of dplyr (0.7.2) than me?:

> dat %>% select(pp)
# A tibble: 6 x 2
  `YY_164.XXX-ad` `YY_165.XXX-ad`
            <dbl>           <dbl>
1           0.004           0.022
2           0.000           0.001
3           0.000           0.000
4           0.001           0.001
5           0.001           0.002
6           0.001           0.000

You need to use the .dots = argument to enclose your var names :

pp <- c("YY_164.XXX-ad","YY_165.XXX-ad")
dat %>% 
  select(.dots = pp)
# A tibble: 6 x 2
.dots1 .dots2
<dbl>  <dbl>
  1  0.004  0.022
2  0.000  0.001
3  0.000  0.000
4  0.001  0.001
5  0.001  0.002
6  0.001  0.000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM