grep() to search column names of a dataframe

前端 未结 2 1014
灰色年华
灰色年华 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"
    

提交回复
热议问题