Select 每年有数据的变量的所有值

Select all values of a variables for which there is data for every year

假设我有一些数据,其中有 2 个数字变量,范围从 0 到 1 (it1, it2),一个名称变量,它有数字变量所属的主题的名称,然后是每个度量的一些日期,范围从 2014 年到 2017 年。现在,我想做的是创建一个数据集,该数据集只包含对我的每一年都有价值的人的衡量标准,然后在未来可能指定我只想要对有数据的人的衡量标准从 2015 年到 2017 年不等。有人对什么包或代码可以帮助我解决问题有任何提示吗?提前致谢。

date <- c("2015-11-26", "2015-12-30","2016-11-13", "2014-09-22", "2014-01-13", "2014-07-26", "2016-11-26", "2016-04-04", "2017-04-09", "2017-02-23", "2015-03-22")
names <- c("Max", "Allen", "Allen", "Bob", "Max", "Sarah", "Max", "Sarah", "Max", "Sarah", "Sarah")
it1 <- c(0.6, 0.3, 0.1, 0.2, 0.3, 0.8, 0.8, 0.5, 0.5, 0.3, 0.7)
it2 <- c(0.5, 0.8, 0.1, 0.4, 0.4, 0.4, 0.5, 0.8, 0.6, 0.5, 0.4)

date <- as.Date(date, format = "%Y-%m-%d")

myframe <- data.frame(date, names, it1, it2)

期望的输出:

date <- c("2015-11-26", "2014-01-13", "2014-07-26", "2016-11-26", "2016-04-04", "2017-04-09", "2017-02-23", "2015-03-22")
names <- c("Max", "Max", "Sarah", "Max", "Sarah", "Max", "Sarah", "Sarah")
it1 <- c(0.6, 0.3, 0.8, 0.8, 0.5, 0.5, 0.3, 0.7)
it2 <- c(0.5, 0.4, 0.4, 0.5, 0.8, 0.6, 0.5, 0.4)

date <- as.Date(date, format = "%Y-%m-%d")

myframe <- data.frame(date, names, it1, it2)
library(lubridate)
myframe[with(data = myframe[year(myframe$date) >= 2014 & year(myframe$date) <= 2017,],
             expr = ave(year(date), names, FUN = function(x)
                 all(year(date) %in% x))) == 1,]
#         date names it1 it2
#1  2015-11-26   Max 0.6 0.5
#5  2014-01-13   Max 0.3 0.4
#6  2014-07-26 Sarah 0.8 0.4
#7  2016-11-26   Max 0.8 0.5
#8  2016-04-04 Sarah 0.5 0.8
#9  2017-04-09   Max 0.5 0.6
#10 2017-02-23 Sarah 0.3 0.5
#11 2015-03-22 Sarah 0.7 0.4

创建 table 年与名称的关系,并为所有年份中的这些名称创建 select 行。没有使用包。

tab <- table(as.POSIXlt(myframe$date)$year + 1900, myframe$names)
subset(myframe, names %in% colnames(tab)[colSums(sign(tab)) == nrow(tab)])

给予:

         date names it1 it2
1  2015-11-26   Max 0.6 0.5
5  2014-01-13   Max 0.3 0.4
6  2014-07-26 Sarah 0.8 0.4
7  2016-11-26   Max 0.8 0.5
8  2016-04-04 Sarah 0.5 0.8
9  2017-04-09   Max 0.5 0.6
10 2017-02-23 Sarah 0.3 0.5
11 2015-03-22 Sarah 0.7 0.4