首页 > 解决方案 > 整个数据帧的条件计数和分组

问题描述

我有这个数据框:

> df <- data.frame(Semester = sample(1:4, 20, replace=TRUE),
                  X1 = sample(c(1:7,NA), 20, replace =TRUE),
                  X2 = sample(c(1:7,NA), 20, replace =TRUE),
                  X3 = sample(c(1:7,NA), 20, replace =TRUE),
                  X4 = sample(c(1:7,NA), 20, replace =TRUE),
                  X5 = sample(c(1:7,NA), 20, replace =TRUE),
                  X6 = sample(c(1:7,NA), 20, replace =TRUE),
                  X7 = sample(c(1:7,NA), 20, replace =TRUE),
                  stringsAsFactors = FALSE)
> df
   Semester X1 X2 X3 X4 X5 X6 X7
1         4  3  7 NA NA  1  2  7
2         3 NA  3 NA  4  3  2  6
3         1  2  5  3  4  7 NA  2
4         3  1  1  6  1  3  2  4
5         1  1  2  1  3  2  6  5
6         2  1  7  1  5  2  2  6
7         4  7  6  5  2  7  1  2
8         1  5  5  7  4  5  1  5
9         1  3  1  1  5  6  3  7
10        3  6 NA  1  1  5 NA  2
11        1  1  6  6  6  3  5  7
12        3  1  5  1  2  3  1 NA
13        4  1  4  1  1  5  6  1
14        1  5  4  4 NA  5  3  3
15        2  2 NA  4  1  1  5  4
16        3  6  7  6  7  3  3  7
17        1  1  2  4  5  4  5  3
18        4  4  7  7  6 NA  4 NA
19        3  4  2  3  4  4  3  5
20        2  1 NA  3  5  7 NA  6

我试图得到这个输出,所有变量n_*的数量在哪里。例如,for是值为 7 的计数(此输出只是参考,值是人为的)。n_*X*n_7Semester==1X*

Semester n_7 n_6 n_5 n_4 n_3 n_2 n_1
       1   5   7   1   5   7   7   7 
       2   4   10  1   3   6   3   4 
       3   5   5   2   5   3   3   2
       4   3   9   10  5   7   0   0

我试过by()了,但它也计算了的值Semester。有没有其他方法可以做到这一点?:

by(df, df$Semester,function(df){
  count_if(eq(7), df)
  count_if(eq(6), df)
  count_if(eq(5), df)
  count_if(eq(4), df)
  count_if(eq(3), df)
  count_if(eq(2), df)
  count_if(eq(1), df)})

标签: rdplyrdata-manipulation

解决方案


你可以使用一种dcast() melt()方法。

library(data.table)
dcast(melt(df, "Semester"), Semester ~ value, fun=length)[-9]
#   Semester 1 2  3 4 5 6 7
# 1        1 5 8 10 2 7 8 4
# 2        2 8 6  7 2 5 2 5
# 3        3 2 1  4 3 2 4 5
# 4        4 1 1  3 4 7 2 8

推荐阅读