根据R中的值从矩阵返回列名 [英] Returning Column Name from Matrix based on value in R
问题描述
我有一个矩阵,希望根据该值提取列名.在这种情况下,我想要包含小于或等于2的值的任何列的名称(无论该值位于哪一行).
I have a matrix that I want to extract column names based on the value. In this case I want the name of any column that contains a value less than or equal to 2 (doesnt matter what row that value is located in).
set.seed(42)
DF <- matrix(sample(1:9,9),ncol=3,nrow=3)
DF <- as.data.frame.matrix(DF)
这是我尝试过的方法((如果矩阵中只有1行,这似乎可以奏效)
this is what I have tried, (it seems to work if there is only 1 row in the matrix)
test<-colnames(DF)[which(DF<=2),]
然后
test将表示包含值< = 2
test would then represent the column names containing values <= 2
推荐答案
1
在列上运行sapply
并找到min
,然后检查min
是否满足您的条件.
1
Run sapply
over columns and find min
and then check if the min
meets your condition.
colnames(DF)[sapply(DF, min) <= 2]
#[1] "V3"
2
您还可以在列(MARGIN = 2
)上运行apply
,以查看每列中的any
值是否满足要求的条件
2
You can also run apply
on columns (MARGIN = 2
) to see if any
value in each column meets the required condition
colnames(DF)[apply(DF, MARGIN = 2, function(a) any(a<=2))]
#[1] "V3"
3
将arr.ind = TRUE
与which
一起使用.这将给出满足which
条件的值的索引.从中提取列信息[,2]
.
3
Use arr.ind = TRUE
with which
. This will give the indices of the values that meet the condition of which
. From that, extract the column information [,2]
.
unique(colnames(DF)[which(DF<=2, arr.ind = TRUE)[,2]])
#[1] "V3"
数据
set.seed(42)
DF <- matrix(sample(1:9,9),ncol=3,nrow=3)
DF <- as.data.frame.matrix(DF)
DF
# V1 V2 V3
#1 9 5 6
#2 8 4 1
#3 3 7 2
这篇关于根据R中的值从矩阵返回列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!