dplyr::select_if can use colnames and their values at the same time?

前端 未结 1 1374
遥遥无期
遥遥无期 2021-01-02 21:33

I want to select cols using colnames and their values in a single pipe chain without referring other objects, such as NAMES <- names(d). Can I do it with

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 21:57

    A workaround that is not too complicated is:

    d %>% select_if(stringr::str_detect(names(.), "Petal") | sapply(., mean) > 5)
    
    # or 
    d %>% select_if(grepl("Petal",names(.)) | sapply(., mean) > 5)
    

    Which gives:

    # A tibble: 150 x 3
       Sepal.Length Petal.Length Petal.Width
                             
     1          5.1          1.4         0.2
     2          4.9          1.4         0.2
     3          4.7          1.3         0.2
     4          4.6          1.5         0.2
     5          5.0          1.4         0.2
     6          5.4          1.7         0.4
     7          4.6          1.4         0.3
     8          5.0          1.5         0.2
     9          4.4          1.4         0.2
    10          4.9          1.5         0.1
    # ... with 140 more rows
    

    0 讨论(0)
提交回复
热议问题