【问题标题】:Count Unique in each list column每个列表列中的唯一计数
【发布时间】:2021-02-05 01:08:37
【问题描述】:

我有一个数据框,其中包含由 str_extract_all() 创建的列表列。我正在尝试确定存在超过 1 个唯一值的情况

#Input =
#                         List
#1:                apple,apple
#2:               apple,banana
#3: apple,orange,orange,banana``


dat<-data.table::data.table(
          List = list(c("apple","apple"),
                   c("apple","banana"),
                   c("apple","orange","orange", "banana")),
  Count_Unique = c(1L, 2L, 3L),
  Multi = c(FALSE, TRUE, TRUE)
)

我尝试了 dplyr::mutate(Count_Unique = length(unique(List)),但这只是给了我整个数据集的唯一变量的数量。我确信它非常简单,我只是不知道如何如果可能,请使用 tidyverse 方法以逐行方式执行此操作。

#Expected Output =
#                         List Count_Unique Multi
#1:                apple,apple            1 FALSE
#2:               apple,banana            2  TRUE
#3: apple,orange,orange,banana            3  TRUE

dat<-data.table::data.table(
          List = list(c("apple","apple"),
                   c("apple","banana"),
                   c("apple","orange","orange", "banana")),
  Count_Unique = c(1L, 2L, 3L),
  Multi = c(FALSE, TRUE, TRUE)
)

【问题讨论】:

    标签: r dplyr tidyverse stringr


    【解决方案1】:

    你可以使用map_dbl

    library(dplyr)
    library(purrr)
    
    dat %>% mutate(Multi = map_dbl(List, n_distinct) > 1)
    
    #                         List Count_Unique Multi
    #1:                apple,apple            1 FALSE
    #2:               apple,banana            2  TRUE
    #3: apple,orange,orange,banana            3  TRUE
    

    使用基础 R:

    dat$Multi <- sapply(dat$List, function(x) length(unique(x))) > 1
    

    或者在data.table

    library(data.table)
    setDT(dat)[, Multi := sapply(List, function(x) length(unique(x))) > 1]
    

    【讨论】:

      【解决方案2】:

      使用data.table

      library(data.table)
      setDT(dat)[, multi := unlist(lapply(List, uniqueN)) > 1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 2019-04-05
        相关资源
        最近更新 更多