如何选择包含R中所选行的特定值的列?

时间:2017-04-14 08:05:04

标签: r subset

我有一个看起来像这样的数据集

Site <- c(1,2,3,4,5,6,7,8,9,10,"kingdom","phylum","class")
A <- c(0,0,1,2,4,5,6,7,13,56,"Eukaryota","Arthropoda","Insecta")
B <- c(1,0,0,0,0,4,5,7,7,8,"Eukaryota","Arthropoda","Insecta")
C <- c(2,3,0,0,4,5,67,8,43,21,"Eukaryota","Arthropoda","")
D <- c(134,0,0,2,0,0,9,0,45,55,"Eukaryota","Arthropoda","Arachnida")
site.species.sample <- data.frame(Site,A,B,C,D)

我想只选择此数据集中的行&#34; class&#34;是&#34; Insecta&#34; (即,在该示例中,仅A列和B列满足该条件)。我试过这段代码:

site.species.sample <- site.species.sample[,site.species.sample["class",]=="Insecta"]

但得到了一个错误:

Error in `[.data.frame`(site.species.sample, , site.species.sample["class",  : 
undefined columns selected

那我该怎么办?感谢

1 个答案:

答案 0 :(得分:1)

以下是一个选项

site.species.sample[,c(TRUE,subset(site.species.sample[,-1],site.species.sample$Site=="class")=="Insecta")]

Site          A          B
1        1          0          1
2        2          0          0
3        3          1          0
4        4          2          0
5        5          4          0
6        6          5          4
7        7          6          5
8        8          7          7
9        9         13          7
10      10         56          8
11 kingdom  Eukaryota  Eukaryota
12  phylum Arthropoda Arthropoda
13   class    Insecta    Insecta