如果你喜欢的话,这是一个丑陋/混乱的方法,但它能完成任务。任何更快、更整洁的方法都会更好。
n<-nrow(DataAlignment)
Newdata<-matrix(0,5148,ncol(DataAlignment))
loops<-ncol(DataAlignment)-1
for(i in 1:loops){
nhat<-which(DataAlignment[1,i+1]==DataAlignment[,1]) #finds the position of the first date in column 2 according to the first column
nend<-which(DataAlignment[n,1]==DataAlignment[,i+1]) #finds the position of last date in col 2 according to the first column
if(nhat==1 | nend != 5148){ #takes into account when they start at the same time but end in different dates
Newdata[,i+1]<-c(DataAlignment[c(1:nend),i+1],rep(NA,n-nend))
}
else{if(nhat==1| nend==5148){Newdata[,i+1]<-c(DataAlignment[,i+1])} #this takes account when they start and end at the same time
else{if(nhat!=1){
Newdata[,i+1]<-c(rep(NA,nhat-1),DataAlignment[c(1:nend),i+1])}}} #creates the new data
}