繁体   English   中英

按R中的年份和列号过滤

[英]Filter by year and column number in R

我对R比较新,我试图按年和特定的列号过滤数据框。 这是我的数据集的玩具示例:

Year    UniqueID       Bench.St   SiteEUI
2011      1              Yes        450
2011      2               No        300
2011      3               No         NA
2011      4               NA        350
2012      1               No        400
2012      2              Yes        200
2013      1              Yes        500
2013      2               No        100
2013      3              Yes        475

我试图通过UniqueIDs提取从2011年到2013年重复信息的行。 使用上面的示例,2011有4个UniqueID(1,2,3,4),2012有2个UniqueID(1,2),2013有3个UniqueID(1,2,3)。 由于UniqueIDs 1和2在三年内出现,我想提取那些年份的UniqueID行。 因此,上面的数据集简化为:

Year    UniqueID        Bench.St        SiteEUI
2011      1               Yes              450
2011      2                No              300
2012      1                No              400
2012      2               Yes              200
2013      1               Yes              500
2013      2                No              100    

我相信dplyr或其他一些简单的功能可能能够做到这一点,但我不知道如何去做。 谢谢!

我想你要问的是如何提取数据所有年份中存在的观察单位集。 下面是一个使用基数R的方法,用于名为dataSet的data.frame:

# get a table of the frequency counts of each ID
idCount <- table(dataSet$uniqueIDs)
# keep the IDs (converted back to integers) that have the most counts
keepIDs <- as.integer(names(idCount))[idCount == max(idCount)]
# save the new data set that includes those IDs
newDataSet <- dataSet[dataSet$uniqueIDs %in% keepIDs,]

您可以split数据集split多年,并使用mergeall = FALSE (默认值)将生成的年度列表条目重新混合在一起。 像这样,你最终得到了在调查的所有年份中存在的'uniqueID'值。

## sample data
dat <- data.frame(Year = c(rep(2011, 4), rep(2012, 2), rep(2013, 3)), 
                  UniqueID = c(1, 2, 3, 4, 1, 2, 1, 2, 3), 
                  Bench.St = c("Yes", "No", "No", NA, "No", "Yes", "Yes", "No", "Yes"), 
                  SiteEUI = c(450, 300, NA, 350, 400, 200, 500, 100, 475))

## split data by year and merge by 'uniqueID', discard non-matching entries
lst <- split(dat, dat$Year)

mrg <- Reduce(function(...) merge(..., by = "UniqueID"), lst)

## subset data based on remaining values of 'uniqueID'
dat[dat$UniqueID %in% mrg$UniqueID, ]

  Year UniqueID Bench.St SiteEUI
1 2011        1      Yes     450
2 2011        2       No     300
5 2012        1       No     400
6 2012        2      Yes     200
7 2013        1      Yes     500
8 2013        2       No     100

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM