问题描述
我需要创建不同的数据框,在for循环中用rbind存储不同的数据框,每个i对应一个。
这里有个例子:
library(lubridate)
DATA <- data.frame("ID"=c("01","01","02","03","04","05","06","06"),"x"=c("2009","2012","2013","2009","2011","2010","2013"),"y"=c("a","a","b","c","c"))
one <- c("a","c")
two <- c("2009","2012")
listofdfs <- list()
for (i in one) {
for (j in 1:(length(two)-1)) {
B <- NULL
A <- DATA[DATA$x %in% c(two[j],two[j+1]) & DATA$y==i,]
# keep the oldest date
tmp<-as.Date(A$x,"%Y-%m-%d")
if (length(tmp)>0)
{
A$tag <- 0
names(tmp)<-1:nrow(A)
id_x <- as.numeric(tapply(tmp[year(tmp)>two[j]],A$ID[year(tmp)>two[j]],function(x){
id <- which.min(x)
names(x)[id]
}))
A$tag[id_x] <- 1
}
# aggregate datasets over different years
B <- rbind(B,A)
}
listofdfs[[i]] <- B
}
除了B之外,几乎所有其他我都想获得,因为B不是不同A的集合(每次都会覆盖A)。
我获得了这样的列表:
$a
ID x y tag
2 01 2012 a 0
6 03 2011 a 0
$b
ID x y tag
15 06 2011 b 0
$c
ID x y tag
5 03 2012 c 0
11 05 2011 c 0
由于覆盖(我不想要)而没有出现2010。
有什么主意吗?谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)