Kelsey
Kelsey

Reputation: 199

How to edit values based on another column's value

I want to selectively edit columns with the prefix grade. I only want to keep values for these columns where days is equal to "0 days" or "1 days". I want to assign the rest of the values as NA.

I have tried using mutate and ifelse, but can't get the combination quite right.

data <- data.frame(
"grade_a" = c(1,3,4,2,3), 
"grade_b" = c(8,6,5,7,8), 
"name_c" = c("Sarah", "Joe", "Dave", "Annie", "Thomas"), 
"days" = c("0 days", "4 days", "5 days", "1 days", "0 days"))

This is the output I am looking for:

results <- data.frame(
"grade_a" = c(1,NA,NA,2,3), 
"grade_b" = c(8,NA,NA,7,8), 
"name_c" = c("Sarah", "Joe", "Dave", "Annie", "Thomas"), 
"days" = c("0 days", "4 days", "5 days", "1 days", "0 days"))

Upvotes: 0

Views: 57

Answers (3)

Marcos P&#233;rez
Marcos P&#233;rez

Reputation: 1250

You can use across function like this:

library(dplyr)
data %>% mutate(across(.cols = starts_with("grade"),.fns = ~if_else(days %in%c("0 days","1 days"),.,NA_real_)))

Upvotes: 0

Anoushiravan R
Anoushiravan R

Reputation: 21938

You can also use case_when as you mentioned:

data %>%
  rowwise() %>%
  mutate(across(grade_a:grade_b, ~ case_when(
    days %in% c("0 days", "1 days") ~ .x,
    TRUE ~ as.double(NA)
  )))

# A tibble: 5 x 4
# Rowwise: 
  grade_a grade_b name_c days  
    <dbl>   <dbl> <chr>  <chr> 
1       1       8 Sarah  0 days
2      NA      NA Joe    4 days
3      NA      NA Dave   5 days
4       2       7 Annie  1 days
5       3       8 Thomas 0 days

Upvotes: 1

bouncyball
bouncyball

Reputation: 10781

We can use across:

library(tidyverse)

data %>%
    mutate(across(starts_with("grade"),
                  ~ifelse(days %in% c("0 days", "1 days"), ., NA)))

#   grade_a grade_b name_c   days
# 1       1       8  Sarah 0 days
# 2      NA      NA    Joe 4 days
# 3      NA      NA   Dave 5 days
# 4       2       7  Annie 1 days
# 5       3       8 Thomas 0 days

Upvotes: 2

Related Questions