首页 > 解决方案 > 重新编码多个多变量变量

问题描述

这个问题是关于在大型数据集中重新编码多变量变量。由于数据很大并且要对许多变量进行重新编码,我正在寻找一种更灵活的方法来调用所有相关变量并执行重新编码。关于重新编码有许多已解决的问题(例如,在 R 中重新编码多个变量),但这些不适合这个问题的细节。以下是数据示例:

df<-data.frame("id"=c(1:5),
           "ax1"=c(2,1,4,3,4),
           "ax2"=c(7,3,6,2,2),
           "bx1"=c(3,5,7,1,2),
           "bx2"=c(1,3,1,5,2),
           "cx1"=c(1,1,7,1,6),
           "cx2"=c(3,9,5,5,4)) 

例如,我想重新编码ax1,bx1cx1. 在这些变量上,我想分别将 1、2、3、4 重新编码为 0、1、1、0,NA否则重新编码。使用“dplyr”包我试过

df <- df %>%  
 mutate_at( vars(ends_with("x1")),
         list(~ ifelse( . == 1, 0, ifelse(.== 2, 1, ifelse(.==3, 1, ifelse(.==4, 0,NA))))))

但是,这不会产生预期的输出。预期的输出看起来像

   id ax1 ax2 bx1 bx2 cx1 cx2
1  1   1   7   1   1   0   3
2  2   0   3  NA   3   0   9
3  3   0   6  NA   1  NA   5
4  4   1   2   0   5   0   5
5  5   0   2   1   2  NA   4

标签: rdataframesubsetrecode

解决方案


dplyr中,有一个recode专门用于此的功能

library(dplyr)
df %>%  
   mutate_at(vars(ends_with("x1")),
        ~recode(., `1` = 0, `2` = 1, `3` = 1, `4` = 0, .default = NA_real_)))

#  id ax1 ax2 bx1 bx2 cx1 cx2
#1  1   1   7   1   1   0   3
#2  2   0   3  NA   3   0   9
#3  3   0   6  NA   1  NA   5
#4  4   1   2   0   5   0   5
#5  5   0   2   1   2  NA   4

推荐阅读