Getting the column name of a specific cell

Hi, I have the following code and I am looking to extract the column names where a cell satisfies some condition.

I have a matrix named rank and I want to extract the names for each row where ranks are 1, 2, or 3 and save those column names in another matrix.

example code below:

column_names_long <- matrix(ncol = 3, nrow=nrow(rank))
for(i in 1:nrow(rank)){
  for(j in 1:ncol(rank)){
    if(rank[i,j] == 1){
      column_names_long[i,1] <- colnames(rank)[j]
    }else if(rank[i,j]==2){
      column_names_long[i,2] <- colnames(rank)[j]
    } else if(rank[i,j] == 3){
      column_names_long[i,3] <- colnames(rank)[j]
    }
  }
}

There are no errors, however, column_names_long matrix is not populated as all the values remain NA. This has something to do with the global environment and the local environment. But cant figure out the issue.

Any help would be greatly appreciated.

Edit: I am an idiot, I was assigning names to different matrix. The code actually works

Edit: I am an idiot, I was assigning names to different matrix. The code actually works

Welcome to the club!

P.S. Not actually an idiot.

1 Like