【问题标题】:counting unique factors in r计算 r 中的唯一因子
【发布时间】:2011-05-05 02:09:27
【问题描述】:

我想知道在记录的每个出生日期出生的独特水坝的数量。我的数据框类似于这个:

dam <- c("2A11","2A11","2A12","2A12","2A12","4D23","4D23","1X23")
bdate <- c("2009-10-01","2009-10-01","2009-10-01","2009-10-01",
           "2009-10-01","2009-10-03","2009-10-03","2009-10-03")
mydf <- data.frame(dam,bdate)
mydf
#    dam      bdate
# 1 2A11 2009-10-01
# 2 2A11 2009-10-01
# 3 2A12 2009-10-01
# 4 2A12 2009-10-01
# 5 2A12 2009-10-01
# 6 4D23 2009-10-03
# 7 4D23 2009-10-03
# 8 1X23 2009-10-03

我使用了aggregate(dam ~ bdate, data=mydf, FUN=length),但它计算了在特定日期分娩的所有大坝

bdate dam
1 2009-10-01   5
2 2009-10-03   3

相反,我需要这样的东西:

mydf2
  bdate      dam
1 2009-10-01  2
2 2009-10-03  2

非常感谢您的帮助!

【问题讨论】:

    标签: r unique r-factor


    【解决方案1】:

    怎么样:

    aggregate(dam ~ bdate, data=mydf, FUN=function(x) length(unique(x)))
    

    【讨论】:

      【解决方案2】:

      您也可以先对数据运行unique

      aggregate(dam ~ bdate, data=unique(mydf[c("dam","date")]), FUN=length)
      

      那么您也可以使用table 代替aggregate,尽管输出会有些不同。

      > table(unique(mydf[c("dam","date")])$bdate)
      
      2009-10-01 2009-10-03 
               2          2 
      

      【讨论】:

      • +1 先运行unique 的好主意。但是请注意,这仅在 mydf 仅包含 dambdate 时才有效。
      • @Joshua:完全正确。我试图在我的数据上运行,但它无法得到我想要的。您提供的行完全符合我的要求,因为我的数据包含大约 60 个其他变量。
      • 如果您确实有其他变量,那么只需使用您想要的两列。见编辑。
      【解决方案3】:

      这只是一个示例,说明如何思考问题以及解决问题的方法之一。

      split.mydf <- with(mydf, split(x = mydf, f = bdate)) #each list element has only one date.
      # it's just a matter of counting unique dams
      unique.mydf <- lapply(X = split.mydf, FUN = unique)
      #and then count the number of unique elements
      unilen.mydf <- lapply(unique.mydf, length)
      #you can do these two last steps in one go like so
      lapply(split.mydf, FUN = function(x) length(unique(x)))
      
      as.data.frame(unlist(unilen.mydf)) #data.frame is just a special list, so this is water to your mill
      
                 unlist(unilen.mydf)
      2009-10-01                   2
      2009-10-03                   2
      

      【讨论】:

      • 很好的例子:对于那些发现这个线程的问题略有不同的人特别有用,因为它将步骤分开以便于理解。
      【解决方案4】:

      dplyr 中,您可以使用 n_distinct

      library(tidyverse)
      mydf %>%
        group_by(bdate) %>%
        summarize(dam = n_distinct(dam))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-01
        • 1970-01-01
        相关资源
        最近更新 更多