0

I have a list of 10 columns called food.1, food.2... food.10, and was wanting to filter my data for when the food name in any of these 10 columns matched a pre-specified list of carbohydrate foods (bread, rice, potatoes, cake, dough)

I started to write this code below, but I am sure there is an easier way to do it rather than copying out every column for every possible artery name I want to keep. Would a function of sorts work, and how so would this be written?

carb.df= df %>%
  filter(food.1 =="bread"|food.2 =="bread"|
           food.3=="bread"|food.4 =="bread"|
           food.5 =="bread"|food.6 =="bread"|
           food.7 =="bread"|food.8 =="bread"|
           food.9 =="bread"|food.10 =="bread"|
           food.1 =="rice"|food.2 =="rice"|
           food.3=="rice"|food.4 =="rice"|
           food.5 =="rice"|food.6 =="rice"|
           food.7 =="rice"|food.8 =="rice"|
           food.9 =="rice"|food.10 =="rice"|
           food.1 =="cake"|food.2 =="cake"|
           food.3 =="cake"|food.4 =="cake"|
           food.5 =="cake"|food.6 =="cake"|
           food.7 =="cake"|food.8 =="cake"|
           food.9 =="cake"|food.10 =="cake")
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 3
    Really, the solution is to make your data tidy. Don’t use numbered columns, transform the data into long format such that there’s only one column, `food`, which contains 10 rows for every one of your current rows. – Konrad Rudolph Sep 23 '21 at 12:39
  • Hands down better to reshape the data. I would still suggest posting a `dput(df)` or a `dput(head(df, n=10))`, something that we can work with. – Matias Andina Sep 23 '21 at 12:55
  • Amazing thanks. I was clearly overthinking it. Sorted now – ed.code.explorer Sep 23 '21 at 12:59

1 Answers1

1

You may use if_any -

library(dplyr)

values <- c('bread', 'rice', 'cake')
result <- df %>% filter(if_any(starts_with('food'), ~. %in% values))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213