我是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
我正在尝试提取2011年到2013年重复信息的行,这些行按照UniqueID排序。使用上面的示例,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或其他一些简单的功能可能会做到这一点,但我不知道如何去做。谢谢!
答案 0 :(得分:3)
我认为您要问的是如何提取数据所有年份中存在的观察单位集。下面是一个使用base R表示dataSet的方法:
# 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,]
答案 1 :(得分:1)
您可以按年split
数据集,并使用merge
和all = 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