[R] How to subsetting data based on factor levels

arun smartpink111 at yahoo.com
Wed Mar 20 02:39:12 CET 2013


levels(group)
#[1] "A" "C"
 levels(group)=="A"
#[1]  TRUE FALSE
a[,group=="A"]
#     A AB
#[1,] 1  6
#[2,] 2  7
#[3,] 3  8
#[4,] 4  9
#[5,] 5 10
a[,group=="C"]
#      C CD
#[1,] 11 16
#[2,] 12 17
#[3,] 13 18
#[4,] 14 19
#[5,] 15 20
a[,match(group,levels(group))==1]
#     A AB
#[1,] 1  6
#[2,] 2  7
#[3,] 3  8
#[4,] 4  9
#[5,] 5 10




A.K.



----- Original Message -----
From: capricy gao <capricyg at yahoo.com>
To: r-help <r-help at r-project.org>
Cc: 
Sent: Tuesday, March 19, 2013 9:19 PM
Subject: [R] How to subsetting data based on factor levels



Here are the code and results
============
> a=matrix(1:20,5)
> a
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
> colnames(a)=c("A","AB","C","CD")
> a
     A AB  C CD
[1,] 1  6 11 16
[2,] 2  7 12 17
[3,] 3  8 13 18
[4,] 4  9 14 19
[5,] 5 10 15 20
> group=factor(substring(colnames(a),1,1))
> group
[1] A A C C
Levels: A C
> a[,levels(group)=="A"]
     A  C
[1,] 1 11
[2,] 2 12
[3,] 3 13
[4,] 4 14
[5,] 5 15
> a[,levels(group)=="C"]
     AB CD
[1,]  6 16
[2,]  7 17
[3,]  8 18
[4,]  9 19
[5,] 10 20

==============
But, I was expect that:
a[,levels(group)=="A"]
     A  AB
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10

Could anybody explain why? Thanks a lot!!
    [[alternative HTML version deleted]]


______________________________________________
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