3

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)

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 would then represent the column names containing values <= 2

d.b
  • 32,245
  • 6
  • 36
  • 77
StevenL
  • 99
  • 1
  • 1
  • 11

3 Answers3

3

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

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

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"

DATA

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
d.b
  • 32,245
  • 6
  • 36
  • 77
2

We can also use colMins/rowMins from matrixStats

library(matrixStats)
names(DF)[rowMins(t(DF))<=2]
#[1] "V3"

Or using tidyverse

library(dplyr)
DF %>% 
    summarise_each(funs(min(.) <=2)) %>% 
    unlist %>% 
    names(.)[.]
#[1] "V3"
akrun
  • 874,273
  • 37
  • 540
  • 662
0

We don't need any apply loops. We can take the unique values of the result of col() when used on the condition DF <= 2.

names(DF)[unique(col(DF)[DF <= 2])]
# [1] "V3"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245