【问题标题】:table of unique observations in R [duplicate]R中的独特观察表[重复]
【发布时间】:2015-02-23 10:47:01
【问题描述】:

我有两个因子变量 - 在名为“数据”的 data.frame 中 - 看起来像这样:

brand  Country
 "A"    "ITA"
 "A"    "ITA"
 "C"    "SPA"
 "B"    "POR"
 "C"    "SPA"
 "B"    "POR"
 "A"    "ITA"
 "D"    "ITA"
 "E"    "SPA"
 "D"    "ITA"

我想要一个表格,列出country 的唯一brands 的数量。 按照这个例子应该是:

# of unique brands  Country
        2             "ITA"
        2             "SPA"
        1             "POR"

首先,我试过了:

data$var <- with(data, ave(brand, Country, FUN = function(x){length(unique(x))}))

但它不适用于因子,所以我转换了我的因子:

data$brand_t<-as.character(data$brand)
data$Country_t<-as.character(data$Country)

然后又一次:

data$var <- with(data, ave(brand_t, Country_t, FUN = function(x){length(unique(x))}))

现在,如果我申请unique(data$var),我会得到"2", "2", "1",这是正确的,但我无法获得我想要的表格。 可能很傻,但我无法解决。

我也想知道是否有更聪明的方法来代替使用因子。

再次感谢。

【问题讨论】:

    标签: r unique factors


    【解决方案1】:

    这里有两种使用data.table v >= 1.9.5dplyr 的快速方法

    library(data.table)
    setDT(df)[, uniqueN(brand), by = Country]
    

    或者

    library(dplyr)
    df %>%
      group_by(Country) %>%
      summarise(n = n_distinct(brand))
    

    或以 R 为基数

    aggregate(brand ~ Country, df, function(x) length(unique(x)))
    

    或者

    tapply(df$brand, df$Country, function(x) length(unique(x)))
    

    或者,如果您喜欢基本 R 的简单语法,并且您的数据集不是太大,您可以结合以下方法

    aggregate(brand ~ Country, df, uniqueN) 
    

    或者

    aggregate(brand ~ Country, df, n_distinct)
    

    【讨论】:

    • 谢谢。此外,对我来说,研究不同的解决方案也是卓有成效的。 'dplyr'中的'%>%'是什么意思?
    • 是管道操作员看看Chaining下的here
    • aggregate 在回答“data.table”和“dplyr”? by 在哪里?震惊!惊恐的事件! :-)
    • unique 有多快?为什么不aggregate(brand ~ Country, unique(mydf), length)
    • 换句话说,只需在新的 R 会话中运行 library(devtools); install_github("Rdatatable/data.table", build_vignettes = FALSE),然后再次加载 data.table
    【解决方案2】:

    在基础 R 中,您可以尝试将 tableuniquecolSums 结合使用,如下所示:

    colSums(table(unique(mydf)))
    # ITA POR SPA 
    #   2   1   2 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-07
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多