【问题标题】:conditional counting and grouping for the whole dataframe整个数据帧的条件计数和分组
【发布时间】:2019-02-27 11:58:12
【问题描述】:

我有这个数据框:

> 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_* 是所有X* 变量的数字n_* 的计数。例如,n_7 for Semester==1X* 值为 7 的计数(此输出只是参考,值是人为的)。

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)})

【问题讨论】:

  • gather > summary 按组 > spread。 SO上有很多例子。搜索“wide to long r”、“count by group r”、“long to wide r”。
  • 请以更易读的方式提供您的示例代码(不带“+”。)如果您想包含NA,最好将其放入您的示例数据中,不要手动更改它
  • 请提供您失败的by()方法的代码。
  • 完成!我不知道如何对 NA 进行采样,这就是我手动进行采样的原因。另外,还有 by() 失败的代码。
  • 试试df %&gt;% gather(variable, value, -Semester, na.rm = TRUE) %&gt;% group_by(Semester, value) %&gt;% summarise(n = n()) %&gt;% spread(value, n) 之类的东西,但我似乎与您想要的输出不匹配

标签: r dplyr data-manipulation


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2014-11-20
    • 2015-07-22
    • 2021-04-18
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多