Tito Sanz
Tito Sanz

Reputation: 1362

Recoding multiple variables using tidyverse in R

May be a silly question, I want to recode multiple variable in a tibble with multiple conditions.

Data example:

library(tidyverse)
s <- matrix(sample(1:15, 20, replace = TRUE), ncol = 4)
s <- as_tibble(s)

Which gives something like this:

# A tibble: 5 x 4
     V1    V2    V3    V4
  <int> <int> <int> <int>
1    11     2     5    14
2     5     4    15     5
3    13    15     2     5
4     7    13    15    11
5    11     5    12     3

I want to recode V1, V2, V3 with this conditions, and leaving V4 equal: if the value is less or equal to 5 get 1, if the value is more than 5 but less or equal to 10 get 2 and finally if the value is more than 10 get 3.

The output should look like this:

# A tibble: 5 x 4
         V1    V2    V3    V4
      <int> <int> <int> <int>
    1    3     1     1     14
    2    1     1     3      5
    3    3     3     1      5
    4    2     3     3     11 
    5    3     1     3      3

I know about apply, sapply, vapply, but I would like to recode using functions from tidyverse package and in an elegant way.

Thanks in advance!

Upvotes: 5

Views: 4445

Answers (1)

tbradley
tbradley

Reputation: 2280

To elaborate on @MrFlick comment, you can use mutate_at in conjunction with the case_when function in dplyr. It would look like this:

s %>% 
  mutate_at(vars(V1:V3), 
            function(x) case_when(x <= 5 ~ 1, x <= 10 ~ 2, TRUE ~ 3))

this will give you:

# A tibble: 5 x 4
     V1    V2    V3    V4
  <dbl> <dbl> <dbl> <int>
1     3     1     3     6
2     2     1     1     8
3     2     3     1    14
4     1     3     3    15
5     1     2     3     7

Upvotes: 9

Related Questions