use %in% in operator with select in R

Viewed 90

I have a dataset that I want to calculate each participants participation rate for certain columns (number of non-NAs/total columns). The actual dataset has many columns that I want to ignore.

For this, let's imagine I only want to know the participation rates in the item and score columns (5 columns), ignoring the name and email columns. This code works:

library(tidyverse)

data <- tibble(name = c("Corey", "Sibley", "Justin"),
               item_1 = c(1, 2, NA),
               item_2 = c(1, NA, NA),
               item_3 = c(2, NA, NA),
               item_4 = c(3, 2, NA),
               score = c(NA,NA, 1),
               email = c("on file", "on file", "on file"))

data %>%
  mutate(part_rate = rowSums(!is.na(select(., -c(name, email))))/5 * 100)

But, in the real dataset, I have different denominators (the 5) for different participants, so I want to list the columns to exclude/include only once. I tried this, but it doesn't work:


columns_to_exclude <- c("email", "name")

data %>%
  mutate(part_rate = rowSums(!is.na(select(., !%in% columns_to_exclude)))/5 * 100)

Is there any way to us the in operator within this select so I can avoid copying and pasting the same columns to exclude multiple times?

Thank you!

1 Answers

We can use - in select

library(dplyr)
data %>% 
  mutate(part_rate = rowSums(!is.na(select(., -columns_to_exclude)))/5 * 100)
Related