Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate, across, and case_when

I am having some trouble getting mutate, across, and case_when to function properly, I've recreated a simple version of my problem here:

a <- c(1:10)
b <- c(2:11)
c <- c(3:12)

test <- tibble(a, b, c)

# A tibble: 10 x 3
       a     b     c
   <int> <int> <int>
 1     1     2     3
 2     2     3     4
 3     3     4     5
 4     4     5     6
 5     5     6     7
 6     6     7     8
 7     7     8     9
 8     8     9    10
 9     9    10    11
10    10    11    12

My goal is to replace all of the 3's with 4's, and keep everything else the same. I have the following code:

test_1 <- 
  test %>% 
  mutate(across(a:c, ~ case_when(. == 3 ~ 4)))

# A tibble: 10 x 3
       a     b     c
   <dbl> <dbl> <dbl>
 1    NA    NA     4
 2    NA     4    NA
 3     4    NA    NA
 4    NA    NA    NA
 5    NA    NA    NA
 6    NA    NA    NA
 7    NA    NA    NA
 8    NA    NA    NA
 9    NA    NA    NA
10    NA    NA    NA

It's close but I get NA values where I want to maintain the value in the original tibble. How do I maintain the original values using the mutate across structure?

Thank you in advance!

like image 896
RobBot Avatar asked May 17 '26 11:05

RobBot


2 Answers

What about this?

> test %>%
+   mutate(across(a:c, ~ case_when(. == 3 ~ 4, TRUE ~ 1 * (.))))
# A tibble: 10 x 3
       a     b     c
   <dbl> <dbl> <dbl>
 1     1     2     4
 2     2     4     4
 3     4     4     5
 4     4     5     6
 5     5     6     7
 6     6     7     8
 7     7     8     9
 8     8     9    10
 9     9    10    11
10    10    11    12

or

> test %>%
+   replace(. == 3, 4)
# A tibble: 10 x 3
       a     b     c
   <int> <int> <int>
 1     1     2     4
 2     2     4     4
 3     4     4     5
 4     4     5     6
 5     5     6     7
 6     6     7     8
 7     7     8     9
 8     8     9    10
 9     9    10    11
10    10    11    12
like image 183
ThomasIsCoding Avatar answered May 19 '26 02:05

ThomasIsCoding


In base R, we can do

test[test ==3] <- 4
like image 22
akrun Avatar answered May 19 '26 02:05

akrun