[R] Stack dataframes into a matrix

David Winsemius dwinsemius at comcast.net
Wed Jul 27 08:46:26 CEST 2016


> On Jul 26, 2016, at 8:07 PM, Anamika Chaudhuri <canamika at gmail.com> wrote:
> 
> 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"))

So this is not reproducible but from the description seems like 

do.call( rbind, .... # the list of dataframes might "work" assuming column names are _all_ the same.

-- 
David.
> 
>        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]]
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list