【问题标题】:case_when where replaced columns have different typescase_when 替换的列具有不同的类型
【发布时间】:2022-11-23 01:45:04
【问题描述】:

我正在处理以下需要使用 case_when 的问题。但是,我遇到错误消息Error: must be a logical vector, not a double vector,因为替换的列不是同一类型(由于bind_rows,有些是逻辑的,有些是双重的)。我正在寻找一个干净的解决方案来获得所需的输出。

#set empty dataframe with column names
df <- setNames(data.frame(matrix(ncol = 5, nrow = 0)), c("a", "b", "c","d","e")) 
df_subset <- data.frame(b=c(1,2))
df1 <- bind_rows(df,df_subset)%>%mutate(type="b")
df1
   a b  c  d  e type
1 NA 1 NA NA NA    b
2 NA 2 NA NA NA    b

df1%>%mutate(result=case_when(type=="a"~a,
                              type=="b"~b,
                              type=="c"~c,
                              type=="d"~d,
                              type=="e"~e,
                              T~NA_real_))

Error: must be a logical vector, not a double vector

预期输出:(注意:我并不总是知道 b 列是否有值)

df1%>%mutate(a=NA_real_,
             c=NA_real_,
             d=NA_real_,
             e=NA_real_,
             result=case_when(type=="a"~a,
                              type=="b"~b,
                              type=="c"~c,
                              type=="d"~d,
                              type=="e"~e,
                              T~NA_real_))

#desired output
   a b  c  d  e type result
1 NA 1 NA NA NA    b      1
2 NA 2 NA NA NA    b      2

【问题讨论】:

    标签: r


    【解决方案1】:

    我认为您可能正在寻找:

    df1 %>%
     rowwise() %>%
     mutate(result = get(type))
    
      a         b c     d     e     type  result
      <lgl> <dbl> <lgl> <lgl> <lgl> <chr>  <dbl>
    1 NA        1 NA    NA    NA    b          1
    2 NA        2 NA    NA    NA    b          2
    

    【讨论】:

      【解决方案2】:

      如果您将所有类型都固定为数字,则您的代码可以正常工作。

      解决方案

      df1 %>% 
        mutate(across(a:e, as.numeric)) %>%  # this is the fix
        mutate(result=case_when(type=="a"~a,
                                type=="b"~b,
                                type=="c"~c,
                                type=="d"~d,
                                type=="e"~e,
                                T~NA_real_))
      

      输出

      #>    a b  c  d  e type result
      #> 1 NA 1 NA NA NA    b      1
      #> 2 NA 2 NA NA NA    b      2
      

      【讨论】:

        【解决方案3】:

        我们可能会使用

        library(dplyr)
        df1 %>%
           rowwise() %>%
           mutate(result = cur_data()[[type]]) %>%
           ungroup
        

        -输出

        # A tibble: 2 × 7
          a         b c     d     e     type  result
          <lgl> <dbl> <lgl> <lgl> <lgl> <chr>  <dbl>
        1 NA        1 NA    NA    NA    b          1
        2 NA        2 NA    NA    NA    b          2
        

        【讨论】:

          猜你喜欢
          • 2020-06-12
          • 2020-02-08
          • 1970-01-01
          • 2017-02-27
          • 2012-08-18
          • 1970-01-01
          • 1970-01-01
          • 2021-05-25
          • 1970-01-01
          相关资源
          最近更新 更多