Choose variables based on name (simple regular expression)

前端 未结 3 597
盖世英雄少女心
盖世英雄少女心 2020-12-30 13:03

I would like to incorporate variable names that imply what I should do with them. I imagine a dataframe \"survey\".

library(Rlab) # Needed for rbern() functi         


        
相关标签:
3条回答
  • 2020-12-30 13:25

    The "operators" package allows some Perl-like syntax:

    library(operators)
    
    survey[, colnames(survey) %~% "bern"]
    

    or

    subset(survey, select = colnames(survey) %~% "bern")
    
    0 讨论(0)
  • 2020-12-30 13:33

    You can use grep() with colnames():

    survey[,grep("bern", colnames(survey))]
    
    0 讨论(0)
  • 2020-12-30 13:34

    If you have a series of names you like to grab you can also use match. perhaps you often need variables "pulse", "exercise", "height", "weight" and "age", but they sometimes show up in different places or with other added variables. You can save the vector of common names then match them against the dataframe and have a new df of just your standard columns in the order you want.

    basenames <- c("pulse", "exercise", "height", "weight", "age")
    get.columns <- match(basenames, names(dataframe))
    new.df <- dataframe[,get.columns]
    
    0 讨论(0)
提交回复
热议问题