[R] how to delete some columns from a matrix based on some other indicator variable

Ritwik Sinha ritwik.sinha at gmail.com
Sun Sep 24 16:50:25 CEST 2006


Hi,

The problem might be mode of the vector "r". Try this

D[,as.character(r)=="1"]

But I am not sure that is the problem. Sometimes "factors" tend to
complicate things. Look for "factor" in the R FAQ page.

Ritwik.

On 9/20/06, David Barron <mothsailor at googlemail.com> wrote:
> You don't need a loop.  You could try
>
> > r <- c(0,0,1,1)
> > matD <- matrix(1:12,nrow=3)
> > matD
>      [,1] [,2] [,3] [,4]
> [1,]    1    4    7   10
> [2,]    2    5    8   11
> [3,]    3    6    9   12
>
> > matD[,r==1]
> > matD[,r==1]
>      [,1] [,2]
> [1,]    7   10
> [2,]    8   11
> [3,]    9   12
>
>
> On 20/09/06, Ya-Hsiu Chuang <amichuang at hotmail.com> wrote:
> > Hello,
> >
> > I am not very familiar with R and need help in deleting a few columns in a
> > matrix.
> >
> > Suppose I have a indicator variable called r and it's defined as r = (0, 0,
> > 1, 1). A matrix D is a 3X4 matrix. If I want a new matrix which contains
> > only the columns of D corresponding to the elements of r that equal to 1.
> > how can i write a loop which creat a new matrix that contains only the last
> > 2 columns of D in this case? thanks
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > 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 Barron
> Said Business School
> University of Oxford
> Park End Street
> Oxford OX1 1HP
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> 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.
>


-- 
Ritwik Sinha
Graduate Student
Epidemiology and Biostatistics
Case Western Reserve University

http://darwin.cwru.edu/~rsinha



More information about the R-help mailing list