[R] Accessing values of a matrix

David Winsemius dwinsemius at comcast.net
Mon Feb 22 16:28:36 CET 2010


On Feb 22, 2010, at 8:45 AM, statquant wrote:

>
> Hello Sarah, thanks for answering
> For example if I have the following example
>
> test <- as.data.frame(matrix(c(1,2,3,4, 11,12,13,14,  
> "a","b","b","c"), nrow
> = 3, ncol=3,dimnames = list(c("r1","r2","r3","r4"),NULL))

This is a malformed example. Should be:
 > test <- as.data.frame(matrix(c(1,2,3,4, 11,12,13,14,  
"a","b","b","c"), nrow= 4, ncol=3,dimnames =  
list(c("r1","r2","r3","r4"),NULL))  )
 > test
    V1 V2 V3
r1  1 11  a
r2  2 12  b
r3  3 13  b
r4  4 14  c


>
>   V1 V2 V3
> r1  1 11  a
> r2  2 12  b
> r3  3 13  b
> r4  4 14  c
>
> it is easy to select test <- test[,mylist] with for example mylist <-
> c("V1","V3")
>
>   V1 V3
> r1  1  a
> r2  2  b
> r3  3  b
> r4  4  c
>
> But after how can I restrict test in selecting the rows where the  
> result in
> column V3 are in a list mylist2, with for example mylist2 <- 
> c("b","c","d") ?
> which would give as an example

?"%in%"
?"["
?subset

 > test[test$V3 %in% c("b","c","d"), c("V1","V2")]
    V1 V2
r2  2 12
r3  3 13
r4  4 14

#Or:

 > subset(test, V3 %in% c("b","c","d"), select=c(V1, V3))
    V1 V3
r2  2  b
r3  3  b
r4  4  c

>
>   V1 V3
> r2  2  b
> r3  3  b
> r4  4  c
>
> Regards
> Colin
> -- 
> View this message in context: http://n4.nabble.com/Accessing-values-of-a-matrix-tp1561932p1564533.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org 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.



More information about the R-help mailing list