使用R中的tidyverse重新编码多个变量

Tit*_*anz 2 r dplyr recode tidyverse

可能是一个愚蠢的问题,我想在具有多个条件的tibble中重新编码多个变量.

数据示例:

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

这给出了这样的东西:

# 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
Run Code Online (Sandbox Code Playgroud)

我想用这个条件重新编码V1,V2,V3,并使V4保持相等:如果值小于或等于5得1,如果值大于5但小于或等于10得到2,最后如果值超过10来3.

输出应如下所示:

# 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
Run Code Online (Sandbox Code Playgroud)

我知道应用,sapply,vapply,但我想使用tidyverse包中的函数并以优雅的方式重新编码.

提前致谢!

tbr*_*ley 6

要详细说明@MrFlick注释,您可以mutate_atcase_whendplyr中的函数一起使用.它看起来像这样:

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

这会给你:

# 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
Run Code Online (Sandbox Code Playgroud)