##for nested indexing--always works #In STATA: # Generate a new variable called newcode that counts from 1 to the number of groups(e.g. countries) egen newcode = group(oldcode) #generate time counter: bysort newcode: gen time = _n ######################################################### # #NESTED INDEXING IN R: ##generate new group variable that is a sequence of integers starting ##with 1 uncode<-unique(dat$ccode) for(i in 1:length(uncode)) dat$newcode[which(dat$ccode == uncode[i])]<-i ##generate a time counter: dat<- dat[order(dat$newcode, dat$year) ,] dat$time <- unlist(by(dat$year, list(dat$newcode), function(x) seq(1, length(x)))) dat<-dat[order(dat$time, dat$newcode),] ##write out dat with writeDatafileR: writeDatafileR(dat, "c:/file.address.name.txt") ##DOUBLE LOOP FOR BALANCED PANELS ONLY!!!! ##transform variables into matrices--with correct dimensions. ##in this example there were 29 countries and 28 time points. sepa<-matrix(dat$sepahost, nrow=29, ncol=28) sepal<-matrix(dat$sepahost, nrow=29, ncol=28) ##write file out using writeDatafileR and list writeDatafileR(list(sepahost=sepa, sepalmho=sepal, N=29, J=28), "c:/structure.test.final.txt")