Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get column name that matches specific row value in dataframe

Tags:

r

I am trying to get the column name of each row where the cell value is 1. My attempt did not work however, can anyone offer suggestions?

library(permute)
set.seed(42)
exampledf<- data.frame(allPerms(c(1,2,3,4)))
exampledf<-head(exampledf)

I tried this:

apply(exampledf,2,function(x){
    ll<-x[1]==1
    which(ll==T)
    })

Dataset

  X1 X2 X3 X4
1  1  2  4  3
2  1  3  2  4
3  1  3  4  2
4  1  4  2  3
5  1  4  3  2
6  2  1  3  4

My goal:

X1
X1
X1
X1
X1
X2
like image 564
Rilcon42 Avatar asked Jan 06 '23 04:01

Rilcon42


2 Answers

this is one method:

# construct sample data.frame
set.seed(1234)
df <- data.frame(matrix(
                 c(sample(1:4, 4), sample(1:4, 4), 
                   sample(1:4, 4), sample(1:4, 4)), 
                 ncol=4, byrow=T))
# name data.frame
names(df) <- c(paste0("x", 1:4))

# get names of variables
names(df)[apply(df, 1, function(i) which(i == 1))]

A method suggested by @DavidArenburg that is probably faster (especially for large datasets) is

names(df)[which(df == 1, arr.ind=T)[, "col"]]

because it does not need to use the apply function.

Note: I constructed a different data.frame as I don't have the permute package.

like image 122
lmo Avatar answered Jan 25 '23 15:01

lmo


I hope I get your question right (shouldn't the last matched column be X2 instead of X3?). Bit old school but if I get you right, this should do it.

library(permute)
set.seed(42)
exampledf <- data.frame(allPerms(c(1,2,3,4)))
exampledf <- head(exampledf)

matched_cols = c()
for(i in 1:nrow(exampledf)){
    row <- edf[i, ] == 1
    matched_col <- colnames(exampledf)[row == T] 
    matched_cols = c(matched_cols, matched_col)  
}
matched_cols
like image 41
friep Avatar answered Jan 25 '23 15:01

friep