[R] R Error : DATA to MATRIX

David Winsemius dwinsemius at comcast.net
Fri Mar 23 13:55:38 CET 2012


On Mar 23, 2012, at 2:53 AM, ritwik_r at isical.ac.in wrote:

> Dear Sir/Madam,
>
> I'm getting a problem with a R-code which converts a data frame to a  
> matrix.
>
> It first generate a (m^(n-m) * m) matrix A and then regenerate another
> matrix B having less dimension than A which satisfy some condition.  
> Now I
> wish to assign each row of B to a vector as individual.
>
> My problem is when I set any choice of (n,m) except m=1 it works  
> fine but
> setting m=1 I got the error : Error in B[i, ] : incorrect number of
> dimensions.
>
> Moreover if (n,m) is large (say, (20,8)) I got the error : Error:  
> cannot
> allocate vector of size 3.0 Gb. I know this is due to large  
> dimension of
> matrix A. How to solve this problem.
>
> My code is given below:
>
> **********************************************************************
>
> n=5
> m=3
> R=numeric(0)
> # Generate all possible m-tuple ( variables having range 0 to n  )  
> in a (
> m^(n-m) * m ) matrix
>
> r = expand.grid(rep(list(0:(n-m)), m))
>
> write.table(r,file="test.txt",row.names=FALSE,col.names=FALSE)
>
> a= read.table(file="test.txt",sep="",header=FALSE)
>
> A= data.matrix(a)
>
> #.........................................................................................
>
> # Generate matrix whose rowsum = n-m
>
> meet.crit = apply(A, 1, function(.row) any((sum(.row)) == n-m))      #
> criteron for being rowsum = n
>
> cbind(A, meet.crit)                                                  #
> Checking rowsum = n for each row
> -m
> B=A[meet.crit,]

At this point the default behavior of the "[" function is to return a  
vector rather than a matrix. You need to add drop=FALSE as an  
additional argument. Read the help page for ?"[".

                                  #
> Generate matrix
>
> #.........................................................................................
>
>
> for(i in 1:choose(n-1,m-1)){
> R=B[i,]
> }
>
> ***************************************************************************
>
> Can you please help me how to get rid of these errors. Thanking you in
> advance.
>
> Regards
>
> Ritwik Bhattacharya
>
>
> Senior Research Fellow
> SQC & OR UNIT, KOLKATA
> INDIAN STATISTICAL INSTITUTE

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list