1

I am trying to select columns on multiple conditions: 1. I want to select specific columns but I also want to select variables with specific expressions in their name. I tried this:

df.waste <- w0%>%
  select(council_name, Period, year | contains("households" | "Tonnage"))

So I am trying to select the columns "council_name", "Period", "year" AND all those which contain the expressions "household" OR "Tonnage" in their name.

I tried different things all similar to the one above but I'm not quite getting what I want. Thanks!

1
  • 1
    Try w0 %>% select(council_name, Period, year, contains(c("households", "Tonnage"))) Commented Jun 11, 2020 at 14:55

2 Answers 2

2

Like this?

w0%>%
  select(council_name, Period, year | contains(c("households", "Tonnage")))

# A tibble: 1 x 5
  council_name Period year  householdsabc Tonnageabc
  <lgl>        <lgl>  <lgl> <lgl>         <lgl>     
1 NA           NA     NA    NA            NA 

Data

council_name <- NA
Period <- NA
year <- NA
householdsabc <- NA
Tonnageabc <- NA

w0 <- tibble(council_name, Period, year, householdsabc, Tonnageabc)
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. Was so close and couldn't figure it haha. Thanks!
You're welcome! Also as mentioned by @Darren you can replace | with ,
1

Another option is grep in base R

w0[c(1, 2, grep("households|Tonnage", names(w0)))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.