0

I'm trying to change cell entries when a column and cell meets criteria.

Data:

df <- data.frame(a=c("a", "ab", "ac"), b=c("b", "bc", NA), c=c("c", NA, "cda")) > df a b c 1 a b c 2 ab bc <NA> 3 ac <NA> cda 

Attempt:

> df %>% mutate(across(matches("b", "c"), ~case_when(. %in% "c" & is.na(.) ~ "here", TRUE ~ as.character(.)))) a b c 1 a b c 2 ab bc <NA> 3 ac <NA> cda 

Looking for this:

 a b c 1 a b c 2 ab bc here 3 ac here cda 
0

3 Answers 3

1

Just declare the variables in across, i.e.

df %>% mutate(across(c('b', 'c'), ~replace(., is.na(.), 'here'))) a b c 1 a b c 2 ab bc here 3 ac here cda 
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

library(tidyverse) data.frame(a=c("a", "ab", "ac"), b=c("b", "bc", NA), c=c("c", NA, "cda")) |> mutate(across(everything(), ~if_else(is.na(.), "here", .))) #> a b c #> 1 a b c #> 2 ab bc here #> 3 ac here cda 

Created on 2022-05-11 by the reprex package (v2.0.1)

Comments

0

In base R :

df[, c("b", "c")][is.na(df[, c("b", "c")])] <- "here" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.