【问题标题】:R - programmatically detect NA columns and return stringR - 以编程方式检测 NA 列并返回字符串
【发布时间】:2020-07-18 04:41:09
【问题描述】:

我的脚本有这个符合条件的列向量

cols <- c("country", "phone", "car")

还有这个dataframe

test <-
  data.frame(
    id = c(1, 2, 3),
    country = c("us", NA, "uk"),
    phone = c(1, 1, NA),
    car = c(NA, 0, 1)
  )

目标是使用结果创建一个新列,其中条件将仅基于 cols 变量中存在的列。如果 id 的所有值都是NA,那么 res 应该是 string nothing,如果其中一些不是 NA,那么我需要这个 colnames,如果所有列都不是 NA,那么结果应该是 string all .

result <-
  data.frame(
    id = c(1, 2, 3),
    country = c("us", NA, NA),
    phone = c(1, 1, NA),
    car = c(NA, NA, NA),
    res = c("country, phone", "phone", "nothing")
  )

我只能通过case_when()函数做到这一点

mutate(
    res = case_when(
      !is.na(country) & is.na(phone) & is.na(car)  ~ "country",
      T ~ "?"
    )

【问题讨论】:

    标签: r if-statement dplyr na


    【解决方案1】:

    您可以使用以下代码在 base R(而不是 dplyr)中执行此操作:

    result$res <- apply(result[,cols],1, function(x){paste(cols[!is.na(x)], collapse=", ")})
    result$res[results$res==""] <- "nothing"
    

    【讨论】:

      【解决方案2】:

      您共享的数据不同(testresult)。所以我们将从result 开始,删除res 列。

      library(dplyr)
      result$res <- NULL
      
      result %>%
        mutate_all(as.character) %>%
        tidyr::pivot_longer(cols = cols) %>%
        group_by(id) %>%
        summarise(res = toString(name[!is.na(value)])) %>%
        type.convert() %>%
        left_join(res, by = 'id') %>%
         mutate(res = case_when(res == '' ~ 'nothing', 
                                 stringr::str_count(result, ',') == 
                                 (length(cols) - 1) ~ 'all',
                                  TRUE ~ as.character(result)))
      
      
      # A tibble: 3 x 5
      #     id res            country phone car  
      #  <dbl> <chr>          <fct>   <dbl> <lgl>
      #1     1 country, phone us          1 NA   
      #2     2 phone          NA          1 NA   
      #3     3 nothing        NA         NA NA   
      

      我们获取长格式数据,获取每个ID 具有非NA 值的列名。然后我们将res 列更改为"all""nothing",如果分别有全部或0 个匹配项。

      【讨论】:

        猜你喜欢
        • 2020-10-27
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        相关资源
        最近更新 更多