簡體   English   中英

如何從R中的面板數據框中刪除具有唯一ID的行?

[英]How to delete rows with a unique ID from a panel data frame in R?

我有一個數據表,其中包含可以由唯一ID標識的數千個公司。 它是長格式數據,每個公司應該在不同的年份出現兩次(兩年內的橫截面時間序列)。

但是,並非所有公司都出現在這兩個年度中,因此我試圖創建一個平衡的長格式面板,其中僅保留在這兩個年度中出現的公司。 我該如何完成?

這是一個示例數據表,用於說明問題:

example <- matrix(c(1,1,2,3,3,2013,2016,2013,2013,2016), ncol=2)
colnames(example) <- c('id', 'year')
example.table <- data.table(example)
example.table

   id year
1:  1 2013
2:  1 2016
3:  2 2013
4:  3 2013
5:  3 2016

在該示例中,我需要一個代碼/函數,該代碼/函數可讓我排除ID為“ 2”的公司行,因為它在2016年不匹配。換句話說:我需要一個將每行與如果id列中沒有匹配項,則將前一行和后一行排除在外。

我已經投入了很多時間,但是似乎已經達到了我的R知識的極限,並且希望得到您的支持。 謝謝!

使用dplyr如下:

library(dplyr)
example.table %>%
  group_by(id) %>%
  filter(n() > 1)
# A tibble: 4 x 2
# Groups:   id [2]
     id  year
  <dbl> <dbl>
1     1  2013
2     1  2016
3     3  2013
4     3  2016

我們從整個數據集中創建一個unique 'year'向量,然后檢查'nm1'中的all值是否all 'id'分組的'year'的%in% ,並對該數據進行子集化。

un1 <- unique(example.table$year)
example.table[, .SD[all(un1 %in% year)], id]
#   id year
#1:  1 2013
#2:  1 2016
#3:  3 2013
#4:  3 2016

注意:OP的數據集為data.table ,此處使用的方法為data.table 最初,考慮過使用.SD[uniqueN(year) > 1] ,但這是錯誤的,可能不適用於所有情況

data.tabledplyr解決方案等效的dplyr解決方案

example.table[, if(.N > 1) .SD, id]

   id year
1:  1 2013
2:  1 2016
3:  3 2013
4:  3 2016

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM