[R] Subset Quirk?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Sep 13 23:57:39 CEST 2007


VTLT1999 wrote:
> Hello All,
>
> I am trying to subset a matrix using subset() and it works fine when I use
> matrix notation, but doesn't work when I use established column names. 
> Sample code is below:
>
> library(mvtnorm)
> library(sm)
> library(ltm)
> library(irtoys)
>
> k<- 100
> set.seed(271828)
> t <-
> rmvnorm(n=k,mean=c(-1,0,1),sigma=matrix(c(1,.8,.5,.8,1,.8,.5,.8,1),3,3)) 
>
> colMeans(t)
> var(t)
> pairs(t)
>
> #tview <-edit(t)
>
> t1<-as.matrix(t[,1])
> t2<-as.matrix(t[,2])
> t3<-as.matrix(t[,3])
>
> # write.table(t, file = "c:/ability.dat", sep = " ", row.names=FALSE,
> col.names=FALSE)
>
> N<- nrow(t)
> id <- as.matrix(seq(001,N,1))
>
> assign <- matrix(0,N,6)
> assign[,1:3] <- t[,1:3]
>   for (i in 1:N)
>   {
>     if (t[i,1] < 7) 
>       assign[i,4]=1
>     else 
>       assign[i,4]=0
>       
>     if (t[i,1] < -1)
>       assign[i,5]=2
>     else
>       assign[i,5]=3
>       
>     if (t[i,2] < 0)
>       assign[i,6]=4
>     else
>       assign[i,6]=5
>   }
>
> group <- cbind(id,assign)
> colnames(group) <-c("ID","T1","T2","T3","G1","G2","G3")
>
> #  This command works fine...
>
> g2 <- subset(group,group[,6]==2)
>
> #  This command does not work...
> g2 <- subset(group,G2==2)
>
>
> Any thoughts?  
>
> Oh, so Petr and Uwe don't cry:  R 2.5.1 on XP (SP2).
>
>   
Well, subset() has a method for data frames and another one for 
matrices. The former does something that the latter cannot do (not 
easily, anyways), namely evaluate the subset expression in the data 
frame. The same concept does not exist for matrices.

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list