【问题标题】:Gather dummy variables and recode factors收集虚拟变量并重新编码因子
【发布时间】:2021-12-08 21:56:34
【问题描述】:

我有

df<-data.frame(id=c(1,2,3,4,5),one=c(0,1,0,0,0), two=c(0,0,1,0,0), three=c(0,0,0,1,0), four=c(0,0,0,0,1))
df

我想将虚拟变量一、二、三和四收集到变量 out 中,我想重新编码 out 变量的级别,以便 one="A", two="B", three= "C" 和四个="D"

df.out<-data.frame(id=c(1,2,3,4,5),out=c(NA, "A","B","C","D" ))
df.out

是否可以在 dplyr 中做到这一点?我尝试收集,但我得到不同长度的输出 data.frame,我认为更宽和更长的枢轴不是正确的选择。

df 是更大、更宽和更长的数据框的一部分。我希望能够指定要合并的列以及如何重新编码。理想的 tidyverse 解决方案

我正在寻找与this完全相反的东西

【问题讨论】:

标签: r dplyr tidyverse


【解决方案1】:

你可以的,

LETTERS[ifelse(rowSums(df[-1]) == 0, NA, max.col(df[-1]))]
#[1] NA  "A" "B" "C" "D"

【讨论】:

  • df 是更大、更宽和更长的数据框的一部分。我希望能够指定要合并的列以及如何重新编码。理想的 tidyverse 解决方案
  • 也许分享一个更合适的例子
【解决方案2】:

这是一个想法:

library(tidyverse)
ids <- 1:nrow(df)
df %>%
    mutate(id = ids) %>%
    pivot_longer(cols = one:four) %>%
    filter(value == 1) %>%
    mutate(out = plyr::mapvalues(
        name, 
        from = c("one", "two", "three", "four"), 
        to = LETTERS[1:4])) %>%
    select(-name, -value) %>%
    right_join(tibble(id = ids)) %>%
    arrange(id)
#> Joining, by = "id"
#> # A tibble: 5 × 2
#>      id out  
#>   <int> <chr>
#> 1     1 <NA> 
#> 2     2 A    
#> 3     3 B    
#> 4     4 C    
#> 5     5 D

由reprex package 创建于 2021-10-22 (v2.0.1)

这是否有效,我不确定。我还需要添加一个“id”变量以使其以这种方式工作。

【讨论】:

    【解决方案3】:

    我找不到一步到位的解决方案,但这个解决方案似乎可以为您提供所需的灵活性。

    recode_fn <- function(x) {
      case_when(x == "one" ~ "A", x == "two" ~ "B", x == "three" ~ "C", x == "four" ~ "D", TRUE ~ "!! Error")
    }
    
    df %>% 
      pivot_longer(
        cols=c(one, two, three, four),
        names_to="Variable",
        values_to="Value"
      ) %>% 
      mutate(
        Variable=recode_fn(Variable)
      )
    # A tibble: 20 × 2
       Variable Value
       <chr>    <dbl>
     1 A            0
     2 B            0
     3 C            0
     4 D            0
     5 A            1
     6 B            0
     7 C            0
     8 D            0
     9 A            0
    10 B            1
    11 C            0
    12 D            0
    13 A            0
    14 B            0
    15 C            1
    16 D            0
    17 A            0
    18 B            0
    19 C            0
    20 D            1
    

    【讨论】:

      【解决方案4】:

      dplyr 唯一的解决方案:

      df %>% 
        rename_with(~ c("id", LETTERS[1:4], colnames(df))) %>% 
        mutate(across(2:5, ~case_when(. == 1 ~ cur_column()))) %>% 
        mutate(out = coalesce(A,B,C,D), .keep="unused")
      

      输出:

          id  out
      1  1 <NA>
      2  2    A
      3  3    B
      4  4    C
      5  5    D
      

      【讨论】:

        【解决方案5】:

        您可以编写一个函数,当所有值都为 0 或最大值索引时返回 NA。

        library(dplyr)
        
        return_value <- function(x) {
          if(all(x == 0)) return(NA)
          else which.max(x)
        }
        
        df %>%
          rowwise() %>%
          mutate(out = return_value(c_across(one:four)))
        
        #     id   one   two three  four   out
        #  <dbl> <dbl> <dbl> <dbl> <dbl> <int>
        #1     1     0     0     0     0    NA
        #2     2     1     0     0     0     1
        #3     3     0     1     0     0     2
        #4     4     0     0     1     0     3
        #5     5     0     0     0     1     4
        

        要获取'A'、'B' 等,您可以使用内置的LETTERS。

        df %>%
          rowwise() %>%
          mutate(out = return_value(c_across(one:four))) %>%
          ungroup %>%
          mutate(out = LETTERS[out])
        

        【讨论】:

          猜你喜欢
          • 2012-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-02
          • 2023-03-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多