如何自动计算所有组是否具有相同的行数,如果不是,如何搜索哪个组缺少哪一行

问题描述 投票:0回答:1

我的数据是:

data <- structure(list(country = c("Poland", "Poland", "Poland", "Poland", 
                                 "Poland", "Poland", "Portugal", "Portugal", "Portugal", "Portugal", 
                                 "Portugal", "Portugal", "Spain", "Spain", "Spain", "Spain", "Spain", 
                                 "Spain"), Code = c("POL", "POL", "POL", "POL", "POL", "POL", 
                                                    "PRT", "PRT", "PRT", "PRT", "PRT", "PRT", "ESP", "ESP", "ESP", 
                                                    "ESP", "ESP", "ESP"), year = c(1950, 1951, 1952, 1953, 1954, 
                                                                                   1955, 1950, 1951, 1952, 1953, 1954, 1955, 1950, 1951, 1952, 1953, 
                                                                                   1954, 1955), democracy = c(3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 
                                                                                                              1, 1, 1, 1, 1, 1)), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 
                                                                                                                                                8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L), class = "data.frame")

我的两个向量是:

id.b0 <- c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L)

re.b0 <- c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,  3L, 3L, 3L)

假设我决定将向量和“数据”结合起来,如下:

data <- cbind.data.frame(
data, id.b0,
re.b0)

我收到错误如下:

这是很自然的,因为我之前故意删除了西班牙(1955 年)的一栏。

我的问题如下:

是否可以构建一个代码,自动计算所有国家是否具有相同的年份,如果没有显示哪个国家缺少哪一年(在我的示例中,它必须显示类似“错误 - 西班牙,年份 - 1955” ).

在处理包含多个国家(每个国家都有很多年)的大型数据集时,这将非常有帮助。 否则,我首先会收到一条错误消息,然后我必须手动检查每个国家和每年,这真是一个令人背痛的事情。

r dataframe rstudio
1个回答
0
投票

您可以创建宽格式表格, 使用

pivot_wider()
(tidyverse) 或
dcast()
(data.table)

由于您的样本数据完整,因此它填充了值 1,但对于不完整的数据,缺失的国家/地区-年份组合会出现 NA。

library(data.table)
dcast(setDT(data), country ~ year, value.var = "year", fun.aggregate = length)
# Key: <country>
#   c  ountry  1950  1951  1952  1953  1954  1955
#      <char> <int> <int> <int> <int> <int> <int>
# 1:   Poland     1     1     1     1     1     1
# 2: Portugal     1     1     1     1     1     1
# 3:    Spain     1     1     1     1     1     1
© www.soinside.com 2019 - 2024. All rights reserved.