0

Given a matrix and a certain column index, how can I find all columns equal to that column (or at most t columns vectors equal to that column).

For example:

m=matrix(data=c(2,2,2,2,3,0,2,2), ncol = 4)

equal columns are 1 & 2 & 4

If column index=1 I can retrieve 2 & 4

If t=1 I will get just the second column 2 or the 4-th column .

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Tou Mou
  • 1,270
  • 5
  • 16
  • 6
    How do you even have column 4 when your `ncol` is 3 ? – Ronak Shah Jan 21 '19 at 15:03
  • 1
    Welcome to Stack Overflow! Please provide a [reproducible example in r](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). The link I provided, will tell you how. Moreover, please take the [tour](https://stackoverflow.com/tour) and visit [how to ask](https://stackoverflow.com/help/how-to-ask). Cheers. – M-- Jan 21 '19 at 15:05

2 Answers2

0

I'm assuming you have a typo with how you're creating your example matrix. Here's a straightforward way to get the indices you want.

m=matrix(data=c(2,2,2,2,3,0,2,2), ncol=4)

equal_cols = function(m, col_index){
    out = NULL
    for (i in (1:NCOL(m))[-col_index]){
        if (all(m[,col_index] == m[,i]))
            out = c(out, i)
        }
    return (out)
    }

equal_cols(m, 1)
# 2 4
mickey
  • 2,168
  • 2
  • 11
  • 20
0

Given that ncol =4, uou could use the apply and which function:

m <- matrix(data=c(2,2,2,2,3,0,2,2), ncol=4)
index <- 1

x <- apply(m,2,FUN=function(x){all(x==m[,index])}) %>% which()
x
[1] 1 2 4

But then the index column is included. It can easily be removed using

x[x!=index]
[1] 2 4
  • 1
    Hey, this is a great solution, but I think `all(x == m[, index])` in FUN is more concise. – Darren Tsai Jan 21 '19 at 16:09
  • Thanks you all again . Plz mister how can I get a sub result optimally ( t first equal columns to that column index ) . In my final project , data will be large. I can't go line per line. – Tou Mou Jan 21 '19 at 16:12
  • @TouMou I think `while()` loop will achieve what you want. You can adapt @mickey's `for()` loop to a `while()` version and set when to break the loop by a conditional statement. – Darren Tsai Jan 21 '19 at 17:31
  • Great , i do it like this : equal_cols = function(m, col_index , t){ out = NULL for (i in (1:NCOL(m))[-col_index]){ if (all(m[,col_index] == m[,i])) out = c(out, i) if (length(out) == t ) break } return (out) } – Tou Mou Jan 21 '19 at 18:09
  • 1
    @DarrenTsai Nice, I agree. I've updated the answer to use the all() function instead. It's definitely more concise. – Sæmundur Rögnvaldsson Jan 21 '19 at 19:32