R按照相同的规则重新编码多个变量

时间:2019-10-02 17:21:43

标签: r dplyr recode

data=data.frame("x1"=c(1:10),
                "x2"=c(1:4,4,6:10),
                "x3"=c(1:3,2:5,5:7),
                "x4"=c(21:30),
                "x5"=c(35:44))

recode=c("x1","x2","x3")


data <- data[recode %in% c(4,5)] <- NA

例如,我想存储一组特定的变量,例如在“ recode”中存储x1,x2,x3。然后,我想更改重新编码中所有变量的所有值,以便将4或5的任何值设置为NA。

3 个答案:

答案 0 :(得分:2)

我们需要将replacelapply一起使用

data[recode] <- lapply(data[recode], function(x) replace(x, x %in% 4:5, NA))
data
#   x1 x2 x3 x4 x5
#1   1  1  1 21 35
#2   2  2  2 22 36
#3   3  3  3 23 37
#4  NA NA  2 24 38
#5  NA NA  3 25 39
#6   6  6 NA 26 40
#7   7  7 NA 27 41
#8   8  8 NA 28 42
#9   9  9  6 29 43
#10 10 10  7 30 44

或与dplyr

library(dplyr)
data %>%
   mutate_at(vars(recode), ~ na_if(., 4)) %>%
   mutate_at(vars(recode), ~ na_if(., 5))
#   x1 x2 x3 x4 x5
#1   1  1  1 21 35
#2   2  2  2 22 36
#3   3  3  3 23 37
#4  NA NA  2 24 38
#5  NA NA  3 25 39
#6   6  6 NA 26 40
#7   7  7 NA 27 41
#8   8  8 NA 28 42
#9   9  9  6 29 43
#10 10 10  7 30 44

答案 1 :(得分:0)

使用Map()

data[recode] <- Map(function(x) ifelse(x %in% c(4, 5), NA, x), data[recode])
data
#    x1 x2 x3 x4 x5
# 1   1  1  1 21 35
# 2   2  2  2 22 36
# 3   3  3  3 23 37
# 4  NA NA  2 24 38
# 5  NA NA  3 25 39
# 6   6  6 NA 26 40
# 7   7  7 NA 27 41
# 8   8  8 NA 28 42
# 9   9  9  6 29 43
# 10 10 10  7 30 44

答案 2 :(得分:0)

一种dplyr可能是:

data %>%
 mutate_at(vars(recode), ~ replace(., . %in% 4:5, NA))

   x1 x2 x3 x4 x5
1   1  1  1 21 35
2   2  2  2 22 36
3   3  3  3 23 37
4  NA NA NA 24 38
5  NA NA NA 25 39
6   6  6  4 26 40
7   7  7  5 27 41
8   8  8  5 28 42
9   9  9  6 29 43
10 10 10  7 30 44