[R] Stack dataframes into a matrix

Anamika Chaudhuri canamika at gmail.com
Wed Jul 27 05:07:28 CEST 2016


I have 100 datasets with 20 rows and 2 columns in each dataset.
I am looking for help to produce x and y below as 1000 X 20 matrix and then
repeat that across 100 datasets using R

         library(MASS)
         library(car)
         set.seed(1234)
         library(mixtools)
         library(sp)

        for (k in 1:1){  # k IS THE NO OF DATASETS
        Y <- read.csv(file=paste0("MVNfreq",k,".csv"))

        Y<-as.matrix(Y)
        Y <- ifelse(Y==0,Y+.5,Y)


        Y1<-Y/60 # estimates of p

        #print(Y1)


sigma2<-matrix(c(var(Y1[,1]),cov(Y1[,1],Y1[,2]),cov(Y1[,1],Y1[,2]),var(Y1[,2])),2,2)

        rho<-sigma2[1,2]/sqrt(sigma2[1,1]*sigma2[2,2])
        mean(Y1[,1])
        mean(Y1[,2])

        #within<-matrix(data=0,nrow=20,ncol=1)

        for (rate3 in 1:20){
        rate<-Y1[i,]
        #print(rate)
        rate1<-rate/(1-rate)
        rate2<-log(rate1)

        Sigma11<-(1/(rate[1]*(1-rate[1]))^2)*sigma2[1,1]
        Sigma22<-(1/(rate[2]*(1-rate[2]))^2)*sigma2[2,2]

Sigma12<-(1/((rate[1]*(1-rate[1]))*(rate[2]*(1-rate[2]))))*sigma2[1,2]

        Sigma2<-matrix(c(Sigma11,Sigma12,Sigma12,Sigma22),2,2)

        rate3<-mvrnorm(1000, mu=c(rate2[1],rate2[2]), Sigma2)
        x<-exp(rate3[,1])/(1+exp(rate3[,1]))
        y<-exp(rate3[,2])/(1+exp(rate3[,2]))
        x<-as.data.frame(x)
        stack(x) # Need help to stack x into a single matrix
        print(x)
        print(y)
        }
        }

	[[alternative HTML version deleted]]



More information about the R-help mailing list