grep() to search column names of a dataframe

前端 未结 2 1015
灰色年华
灰色年华 2021-02-06 01:54

Is there a clearer, simpler, more direct, shorter way to do this:

Where df1 is a dataframe:

names(df1[grep(\"Yield\",names(df1))])

I wa

相关标签:
2条回答
  • 2021-02-06 02:01

    grep has a value argument that should work for this. Try:

    grep("Yield", names(df1), value = TRUE)
    

    MRE

    df1 <- data.frame(
      Yield_1995 = 1:5,
      Yield_1996 = 6:10,
      Something = letters[1:5]
    )
    
    ## Your current approach
    names(df1[grep("Yield",names(df1))])
    # [1] "Yield_1995" "Yield_1996"
    
    ## My suggestion
    grep("Yield", names(df1), value=TRUE)
    # [1] "Yield_1995" "Yield_1996"
    

    OK, so it doesn't win in terms of brevity, but it does in terms of clarity of intention :-)


    For the sake of variety.... a "dplyr" approach.

    library(dplyr)
    names(df1 %>% select(contains("Yield")))
    # [1] "Yield_1995" "Yield_1996"
    names(select(df1, contains("Yield")))
    # [1] "Yield_1995" "Yield_1996"
    
    0 讨论(0)
  • 2021-02-06 02:25

    You could easily define your own function to make it shorter. For instance,

     myfun <- function(x,y) names(y[grep(x, names(y))])
    

    Then, whenever you need it, you use

     myfun("Yield", df1)
    

    It hardly gets any shorter.

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