如何按不同标准计算多个变量中的出现次数并按两个变量分组

How to count occurences in several variables by different criteria and grouped by two variables

使用 R,我想计算两个变量在两个变量中出现的次数; IDS 和年份。统计的变量之一需要按唯一值统计。 我真的四处寻找答案,但似乎找不到。 我有一个这样的数据集(尽管包括更多变量):

IDS = c(1,1,1,1,1,1,2,2) 
year = c(1,1,1,1,1,2,1,1) 
x = c(5, 5, 5, 10, 2, NA, 3, 3)
y = c(1, 2, 4, 0, NA, 2, 0, NA)
dfxy = data.frame(IDS, year, x, y)

dfxy
   IDS year   x  y
1   1    1    5  1
2   1    1    5  2
3   1    1    5  4
4   1    1   10  0
5   1    1    2 NA
6   1    2   NA  2
7   2    1    3  0
8   2    1    3 NA

我想计算每个 IDS 和每年在 x 和 y 两列中出现的次数。 x 中的计数需要 x 的唯一值。 我想要这样的输出:

   IDS year x y
1   1    1  3 4
2   1    2  0 1
3   2    1  1 1

它类似于

中cbind的答案

Aggregate / summarize multiple variables per group (i.e. sum, mean, etc)

对我来说会是什么样子

aggregate(cbind(x, y)~IDS+year, data=dfxy, ???)

NA 算作没有出现,任何数字都算作在 y 中出现,在 x 中必须计算每个唯一出现(只要它不是 NA)。 x 和 y 中都没有带 NA 的行。 我试过使用长度而不是总和,但这似乎只能对 x 和 y 的行数进行平均总结。

出点子还是link我能在这个中找到答案吗? 谢谢

我们可以试试dplyr

library(dplyr)
dfxy %>% 
     group_by(IDS, year) %>%
     summarise_each(funs(sum(!is.na(.))))

aggregate中需要指定na.action参数,因为公式界面默认为na.omit,这将排除大部分数据:

aggregate(cbind(x, y) ~ IDS + year, dfxy, 
          FUN = function(x){sum(!is.na(x))}, na.action = na.pass)
##   IDS year x y
## 1   1    1 3 3
## 2   2    1 1 1
## 3   1    2 0 1

对于新问题,添加 unique:

aggregate(cbind(x, y) ~ IDS + year, df, 
          FUN = function(x){sum(!is.na(unique(x)))}, na.action = na.pass)
##   IDS year x y
## 1   1    1 3 4
## 2   2    1 1 1
## 3   1    2 0 1

aggregate(cbind(x, y) ~ IDS + year, df, 
          FUN = function(x){length(unique(na.omit(x)))}, na.action = na.pass)
##   IDS year x y
## 1   1    1 3 4
## 2   2    1 1 1
## 3   1    2 0 1