在R中按组执行频率表,计算值的数量。

3
假设这是我的数据集。
(dput)
dataset<-structure(list(group1 = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 1L, 
1L, 1L), .Label = c("b", "x"), class = "factor"), group2 = structure(c(2L, 
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("g", "y"), class = "factor"), 
    var1 = c(2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L)), .Names = c("group1", 
"group2", "var1"), class = "data.frame", row.names = c(NA, -9L
))

我需要为两个组计算频率。
x+y
b+g

对于变量var1,计算值为1和值为2的数量。对于每个组。

所需的输出结果为:

        total_count_of_group    var1-1  var1-2
x   y          5                   
                              3         2
b   g          4              2         2

这个输出的意思是,总共有x+y=5个观测值在此组中。其中1个值出现了3次,2个值出现了2次。

同样地, 总共有b+g=4个观测值在此组中。 其中1个值出现了2次,2个值出现了2次。

如何得到这样的表格?

5个回答

4
这可以通过两个步骤来解决:
  1. 聚合组总和并更新数据集
  2. 从长格式重塑为宽格式
使用data.table
library(data.table)
dcast(setDT(dataset)[, total_count_of_group := .N, by =. (group1, group2)], 
      group1 + group2 + total_count_of_group~ paste0("var1=", var1), length)
   group1 group2 total_count_of_group var1_1 var1_2
1:      b      g                    4      2      2
2:      x      y                    5      3      2
请注意,这将适用于var1中任意数量的不同值,以及任意数量的组。

3
library(tidyverse)

dataset %>%
  group_by(group1, group2) %>%             # for each combination of groups
  mutate(counts = n()) %>%                 # count number of rows
  count(group1, group2, var1, counts) %>%  # count unique combinations 
  spread(var1, n, sep = "_") %>%           # reshape dataset
  ungroup()                                # forget the grouping

# # A tibble: 2 x 5
#   group1 group2 counts var1_1 var1_2
#   <fct>  <fct>   <int>  <int>  <int>
# 1 b      g           4      2      2
# 2 x      y           5      3      2

1
你可以生成三个表格,选择相关计数,然后将它们合并到一个数据框中。
a <- table(dataset$group1, dataset$group2)
b <- table(dataset$var1[dataset$group1=='x'])
d <- table(dataset$var1[dataset$group1=='b'])

data.frame(total_count_of_group = c(a[2,2], a[1,1]), 
           var1_1 = c(b[1], b[2]),
           var1_2 = c(d[1], d[2]))

  total_count_of_group var1_1 var1_2
1                    5      3      2
2                    4      2      2

1
这是使用基本的R选项:base R
out <- aggregate(cbind(var = rep(1, nrow(df1))) ~ ., 
    transform(df1, counts = ave(var1, group1, group2, FUN = length)), length)
reshape(out, idvar = c('group1', 'group2', 'counts'),
     timevar= 'var1', direction= 'wide')
#   group1 group2 counts var.1 var.2
#1      b      g      4     2     2
#3      x      y      5     3     2

1

Here's a tidyverse solution :

library(tidyverse)
dataset %>%
  group_by(group1, group2) %>%
  summarize(total = n(), x = list(table(var1) %>% as_tibble %>% spread(var1,n))) %>%
  unnest

# # A tibble: 2 x 5
# # Groups:   group1 [2]
#   group1 group2 total   `1`   `2`
#   <fct>  <fct>  <int> <int> <int>
# 1 b      g          4     2     2
# 2 x      y          5     3     2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接