【问题标题】:R recode multiple variables following same rulesR按照相同的规则重新编码多个变量
【发布时间】:2020-02-01 00:26:33
【问题描述】:
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

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

【问题讨论】:

  • data[data[,recode] %in% c(5,6),recode]
  • %in% 在 data.frame 上不起作用。它适用于vectors
  • 谢谢,我正要问为什么这不起作用。所以我可以对重新编码中的所有变量都这样做......
  • 如果你看?"%in%",它是基于matchtable - vector or NULL: the values to be matched against. Long vectors are not supported.

标签: r dplyr recode


【解决方案1】:

我们需要使用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

【讨论】:

  • @akrun;当我使用 lapply 时,它将我的数据框转换为列表。有没有办法避免这种情况发生?
  • @bvowe 如果您查看data[recode] &lt;- ,我们将list 输出分配给数据集的列,使其具有与数据集相同的结构。但是,如果只查看list的结果,它是一个列表,如果不是为了更新原始数据,可以通过包装data.frame(lapply(data[recode], function(x) replace(x, x %in% 4:5, NA)))将其转换为data.frame
【解决方案2】:

使用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

【讨论】:

    【解决方案3】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多