【问题标题】:Dpylr's recode function multiple-to-1 RDpylr的recode函数multi-to-1 R
【发布时间】:2017-12-05 18:34:14
【问题描述】:

我想要一种更简单的方法来重新编码向量。具体来说,我想知道是否有办法将向量传递给像dplyrrecode 这样的函数。我了解准引用的基础知识,但不太了解如何合并=

library(tidyverse)

vec1 <- rep(LETTERS[1:7],7)

#standard way
vec2 <- recode(vec1, 
               "A" = "Value1",
               "B" = "Value2",
               "C" = "Value3",
               "D" = "Value4",
               "E" = "Value5",
               "F" = "Value6",
               "G" = "Value7"
               )

vec3 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value1",
               "C" = "Value2",
               "D" = "Value2",
               .default = "Value other"
               )

我想做以下事情

vec3 <- some.function(vec1,
               c("A", "B") = "Value1",
               c("C", "D") = "Value2",
               .default = "Value other"
               )

我有一个解决方案,但不知道如何将函数与 ...= 合并

do.call(dplyr::recode, 
        c(list(vec1), 
        setNames(rep("Value1",length(val1)), val1), 
        setNames(rep("Value2",length(val2)), val2)))

我还想出了一种方法来传递两个向量并重命名所有变量。

recode.by.vectors <- function(x, current.names, new.names){
  do.call(dplyr::recode, c(list(x), setNames(new.names, current.names)))
}

最后,我知道一个基本解决方案。

vec3 <- vec1
val1 <- c("A", "B")
val2 <- c("C", "D")
vec3[vec1 %in% val1] <- "Value1"
vec3[vec1 %in% val2] <- "Value2"
vec3[!vec1 %in% c(val1,val1)] <- "Value other"

但我不知道如何将此处执行的分配合并到一个函数中。

【问题讨论】:

    标签: r dplyr recode


    【解决方案1】:

    我们可以使用dplyr 包中的case_when

    library(dplyr)
    
    vec1 <- rep(LETTERS[1:7],7)
    
    vec2 <- case_when(
        vec1 %in% c("A", "B")    ~ "Value1",
        vec1 %in% c("C", "D")    ~ "Value2",
        TRUE                     ~ "Value other"
      ) 
    head(vec2)
    # [1] "Value1"      "Value1"      "Value2"      "Value2"      "Value other" "Value other"
    

    【讨论】:

      【解决方案2】:

      使用forcats 包(也包含在tidyverse 包中)

      library(forcats)
      
      vec1 <- rep(LETTERS[1:7], 7)
      
      fct_collapse(vec1,
                   Value1 = c("A", "B"),
                   Value2 = c("C", "D"),
                   `Value other` = c("E", "F", "G"))
      

      如果您有很多类别要放入Value other,这有点麻烦,但是通过第二步,您可以稍微简化一下

      fct_collapse(vec1,
                   Value1 = c("A", "B"),
                   Value2 = c("C", "D")) %>% 
        fct_other(keep = c("Value1", "Value2"),
                  other_level = "Value other")
      

      【讨论】:

        猜你喜欢
        • 2018-12-06
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        • 1970-01-01
        • 2022-12-01
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        相关资源
        最近更新 更多