Reputation: 9765
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
Upvotes: 7
Views: 17423
Reputation: 5
In case the data frame has got multiple values of 1 in these columns it can be achieved using this, though it will one for one value as well
exampledf$results<-c() # Adding one empty column called results here
for(i in (1:nrow(exampledf))){
exampledf$results[i] <- paste((colnames(exampledf)[which(exampledf[i,1:(ncol(exampledf)-1)] == 1)]),collapse = ",")
}
hopefully it would be helpful to this thread
Upvotes: -1
Reputation: 66
Another simple method :
library(permute)
set.seed(42)
exampledf<- data.frame(allPerms(c(1,2,3,4)))
for(i in 1:nrow(exampledf)){
for (j in 1:length(exampledf[i,])){
if(exampledf[i,j]==1){
print(names(exampledf)[j])
}
}
}
The sample output is:
"X1"
"X1"
"X1"
"X1"
"X1"
"X2"
"X2"
"X3"
Upvotes: 0
Reputation: 38500
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.
Upvotes: 11
Reputation: 321
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
Upvotes: 2