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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With