如何在 R 中用列名过滤矩阵的单列?
如果矩阵有列名,要在 R 中过滤矩阵的单列,我们可以简单地使用单个方括号,但这会产生一个没有列名的向量。如果我们想使用列名,那么需要像以下示例中所示,使用 drop=FALSE 参数传递列名或列号。
示例 1
> M1<-matrix(sample(0:1,80,replace=TRUE),ncol=4) > colnames(M1)<-c("V1","V2","V3","V4") > M1
输出
V1 V2 V3 V4 [1,] 0 0 1 0 [2,] 1 1 1 1 [3,] 0 0 0 0 [4,] 0 1 1 0 [5,] 1 1 1 1 [6,] 0 1 1 0 [7,] 0 1 0 1 [8,] 1 1 0 1 [9,] 1 1 0 1 [10,] 0 0 1 0 [11,] 0 0 0 1 [12,] 0 1 0 0 [13,] 0 0 0 0 [14,] 1 0 0 0 [15,] 0 1 0 1 [16,] 0 0 1 0 [17,] 1 1 1 1 [18,] 1 0 1 1 [19,] 1 0 1 1 [20,] 0 0 0 0
从 M1 − 中提取 V1 列
> M1[,"V1",drop = FALSE]
输出
V1 [1,] 0 [2,] 1 [3,] 0 [4,] 0 [5,] 1 [6,] 0 [7,] 0 [8,] 1 [9,] 1 [10,] 0 [11,] 0 [12,] 0 [13,] 0 [14,] 1 [15,] 0 [16,] 0 [17,] 1 [18,] 1 [19,] 1 [20,] 0
示例 2
> M2<-matrix(sample(c("Yes","No"),40,replace = TRUE),ncol=2) > colnames(M2)<-c("Binary1","Binary2") > M2
输出
Binary1 Binary2 [1,] "Yes" "Yes" [2,] "Yes" "No" [3,] "Yes" "No" [4,] "Yes" "Yes" [5,] "Yes" "Yes" [6,] "No" "No" [7,] "Yes" "Yes" [8,] "No" "Yes" [9,] "No" "No" [10,] "Yes" "Yes" [11,] "Yes" "Yes" [12,] "Yes" "No" [13,] "Yes" "No" [14,] "No" "Yes" [15,] "No" "Yes" [16,] "Yes" "Yes" [17,] "No" "Yes" [18,] "Yes" "Yes" [19,] "Yes" "Yes" [20,] "No" "No"
从 M2 − 中提取 Binary2 列
> M2[,"Binary2",drop = FALSE]
输出
Binary2 [1,] "Yes" [2,] "No" [3,] "No" [4,] "Yes" [5,] "Yes" [6,] "No" [7,] "Yes" [8,] "Yes" [9,] "No" [10,] "Yes" [11,] "Yes" [12,] "No" [13,] "No" [14,] "Yes" [15,] "Yes" [16,] "Yes" [17,] "Yes" [18,] "Yes" [19,] "Yes" [20,] "No"
广告