How do I select variables in an R dataframe whose names contain a particular string?

前端 未结 3 927
臣服心动
臣服心动 2020-12-02 20:52

Two examples would be very helpful for me.

How would I select: 1) variables whose names start with b or B (i.e. case-insensitive) or 2) variables whose names contain

3条回答
  •  庸人自扰
    2020-12-02 21:18

    If you just want the variable names:

    grep("^[Bb]", names(df), value=TRUE)
    
    grep("3", names(df), value=TRUE)
    

    If you are wanting to select those columns, then either

    df[,grep("^[Bb]", names(df), value=TRUE)]
    df[,grep("^[Bb]", names(df))]
    

    The first uses selecting by name, the second uses selecting by a set of column numbers.

提交回复
热议问题