How do I select variables in an R dataframe whose

2019-01-08 19:06发布

问题:

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 a 3

df <- data.frame(a1 = factor(c("Hi", "Med", "Hi", "Low"), 
  levels = c("Low", "Med", "Hi"), ordered = TRUE),
  a2 = c("A", "D", "A", "C"), a3 = c(8, 3, 9, 9),
  b1 = c(1, 1, 1, 2), b2 = c( 5, 4, 3,2), b3 = c(3, 4, 3, 4),
  B1 = c(3, 6, 4, 4))

回答1:

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.



回答2:

While I like the answer above, I wanted to give a "tidyverse" solution as well. If you are doing a lot of pipes and trying to do several things at once, as I often do, you may like this answer. Also, I find this code more "humanly" readable.

The dplyr function select_vars will select variables from a character vector in the first argument, which should contain the names of the corresponding data frame, based on a select helper function like starts_with or matches

library(dplyr)

df <- data.frame(a1 = factor(c("Hi", "Med", "Hi", "Low"), 
                         levels = c("Low", "Med", "Hi"), ordered = TRUE),
             a2 = c("A", "D", "A", "C"), a3 = c(8, 3, 9, 9),
             b1 = c(1, 1, 1, 2), b2 = c( 5, 4, 3,2), b3 = c(3, 4, 3, 4),
             B1 = c(3, 6, 4, 4))

#will select the names starting with a "b" or a "B"
select_vars(names(df), starts_with('b', ignore.case = TRUE)) 

#use select in conjunction with the previous code
df %>%
  select(select_vars(names(df), starts_with('b', ignore.case = TRUE)))

#Alternatively
select_vars(names(df), matches('^[Bb]'))

Note that the default for ignore.case is TRUE, but I put it here to show explicitly, and in case future readers are curious how to adjust the code. The can also use the include and exclude arguments are also very useful. For example, you could use select_vars(names(df), matches('^[Bb]'), include = 'a1') if you wanted everything that starts with a "B" or a "b", and you wanted to include "a1" as well.



标签: r grep