[R] subset in a matrix

Peter Ehlers ehlers at ucalgary.ca
Tue Feb 9 21:42:34 CET 2010


As others have said, z[z[, 1] < 0, ] does it. Just in case
you're wondering why your subset command won't work,
str() is your friend (as is so often the case):

str(z)
str(as.data.frame(z))  ## (I don't think that R has 'as.data.set')

So z is a matrix with column *names* "x1", etc;
as.data.frame(z) is a data.frame with *variables* named "x1" etc.

If you really want to use subset(), then

  subset(z, z[, "x1"] < 0, select = <...>)

will work, but I wouldn't use it.

  -Peter Ehlers

DonDiego wrote:
> Hi,
> 
> I have a matrix of data values like the example bellow. I would like to
> extract a subset of the matrix for the values where the first column is
> negative.  I am using the subset function. However, I am getting an error
> message that the conditional variable doe snot exist.  For some reason, the
> subset operation only works if I transform the matrix to a data set using
> as.data.set(). The help indicates that the subset function can be applied to
> matrixes and data sets. I am wondering if anyone has seen a similar problem
> before. am I using the correct syntax?
> 
> 
> 
> n = 15
> m = 5
> 
> cnames = paste("x",1:m,sep="")
> rnames = 1:n
> 
> z = matrix(rnorm(n*m),n,m,dimnames =list(rnames,cnames))
> 
> 
> Thanks,
> 
> Jorge
> 
> 
> 
> 
> test = subset(z,x1 < 0, select = c(cnames))
> 

-- 
Peter Ehlers
University of Calgary



More information about the R-help mailing list