【问题标题】:aggregate by count in r [duplicate]按r中的计数聚合[重复]
【发布时间】:2017-03-29 12:14:38
【问题描述】:

我有一个数据集如下:

Group   Class
  A       1
  A       2
  A       1
  A       1
  B       2
  B       2
  B       2
  B       1
  B       3
  B       1
  C       1
  C       1
  C       1
  C       2
  C       3

我想按“组”列聚合表,“类”列上的值将是具有最大计数的类。比如A组,1出现3次,Class的值为1。同理,Group 2,2出现3次,Class的值为2。结果表如下:

Group   Class
  A       1
  B       2
  C       1

我是 R 编程新手,希望您能帮我解决这个问题。谢谢!

【问题讨论】:

  • aggregate(Class~Group, df1, function(x) which.max(table(x)))
  • 呸,我准备好了相同的答案。打我一分钟。 :)
  • 更一般地,aggregate(Class~Group, df, function(x) {temp <- table(x); names(temp)[which.max(temp)]}) 用于提取更复杂的值,例如类名或在组中没有观察到一个类的情况下。
  • count(df, Group, Class) %>% slice(which.max(n)) 在 dplyr 中也很简单
  • 哇,工作就像一个魅力!非常感谢大家的快速回复,特别感谢@Ronak Shah

标签: r count aggregate frequency


【解决方案1】:

您也可以不使用aggregate 来执行此操作,因此请改用tablemax.col

tb <- table(df$Group, df$Class)
data.frame("Group"=rownames(tb), "CLass"=max.col(tb))

#  Group CLass
#1     A     1
#2     B     2
#3     C     1

这似乎更快:

library(microbenchmark)

# by Ronak Shah in comments
f1 <- function(df) aggregate(Class~Group, df, function(x) which.max(table(x))) 
# this answer
f2 <- function(df) {tb <- table(df$Group, df$Class);
 data.frame("Group"=rownames(tb), "CLass"=max.col(tb));}

all(f1(df)==f2(df))
# [1] TRUE

microbenchmark(f1(df), f2(df))

# Unit: microseconds
   # expr     min       lq     mean   median      uq      max neval
 # f1(df) 800.153 838.9130 923.6484 870.0115 918.988 1981.901   100
 # f2(df) 298.367 319.0995 353.4915 338.6305 380.246  599.439   100

df <- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
    Class = c(1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 3L, 1L, 1L, 1L, 
    1L, 2L, 3L)), .Names = c("Group", "Class"), class = "data.frame", row.names = c(NA, 
-15L))

【讨论】:

  • 非常感谢您的帮助!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2014-04-10
  • 2021-09-17
相关资源
最近更新 更多