r - 按组在多列上汇总唯一值
问题描述
我有以下问题:
我的数据集包含许多不同武器系统(级别)的国家/地区年度观察结果。我想知道每个组(国家)在数据集的时间跨度内有多少不同的系统(唯一值)。
简化后,数据集如下所示:
a <- c("Greece", "Greece", "Belgium", "Belgium", "Germany", "Germany")
b <- c(1980, 1981, 1980, 1981, 1980, 1981)
c1 <- c("Weapon1", "Weapon1", "Weapon5", "Weapon5", "Weapon3", "Weapon2")
d <- c("Weapon2", "Weapon4", "Weapon2", "Weapon2", "Weapon1", "Weapon3")
e <- c("Weapon3", "Weapon3", "Weapon3", "Weapon4", "Weapon2", NA)
df <- data.frame(a,b,c1,d,e)
a b c1 d e
1 Greece 1980 Weapon1 Weapon2 Weapon3
2 Greece 1981 Weapon1 Weapon4 Weapon3
3 Belgium 1980 Weapon5 Weapon2 Weapon3
4 Belgium 1981 Weapon5 Weapon2 Weapon4
5 Germany 1980 Weapon3 Weapon1 Weapon2
6 Germany 1981 Weapon2 Weapon3 <NA>
所以在示例代码中,德国总共部署了 3 种不同的武器系统。我怎样才能做到这一点?
谢谢大家!
解决方案
library(tidyverse)
df %>%
pivot_longer(cols = c(c1, d, e)) %>%
group_by(a) %>%
filter(!is.na(value)) %>%
distinct(value) %>%
summarize(n=n())
这使:
# # A tibble: 3 x 2
# a n
# <chr> <int>
# 1 Belgium 4
# 2 Germany 3
# 3 Greece 4
推荐阅读
- python - 肘部光滑时如何确定最佳kmeans
- tensorflow - 如何快速改变 tensorflow/keras 神经网络的权重?
- sqlite - 查找和删除及时接近的记录
- vba - 操作系统的位数是否重要,或者只是我需要担心的应用程序?
- r - 合并来自同一数据框的行
- django - 如何设置我继承的 virtualenv
- php - 如何更新选定的行?
- identityserver4 - 仅在 IdentityServer4 中注销客户端
- java - DataflowRunner 需要 gcpTempLocation,但无法从 PipelineOptions 检索值
- c++ - 将一个数组传递给所有工作项都相同的内核