2
votes

I have a dataframe that looks like this:

df1<-data.frame(c(0,0,0),c(0,1,0),c(1,0,0))

names(df1)<-c("A","B","C")

  A B C
1 0 0 1
2 0 1 0
3 0 0 0

I would like to substitute the "1" values in df1 for the column names associated with those values, to create a dataframe that looks like this:

  A B C
1 0 0 C
2 0 B 0
3 0 0 0

I tried the following code, but it produced the incorrect dataframe (listed below):

data.frame(ifelse(df==1,colnames(df),0))

  A B C
1 0 0 A
2 0 B 0
3 0 0 0

Any help would be greatly appreciated.

1
df1<-data.frame(c(0,0,0),c(0,1,0),c(1,0,0)) names(df1)<-c("A","B","C") can be replaced by df1<-data.frame(A=c(0,0,0),B=c(0,1,0),C=c(1,0,0)), FYI.prabhasp

1 Answers

4
votes

What is happening is that ifelse is running once per column, and when it comes to replacing an element, it takes the nth element of colnames. But because ifelse is run on each column at a time, indexing colnames ends up matching to the row-index, not to the column-index. In order to get the right solution, ifelse needs to run on the row vectors, not on the column vectors.

Here is one solution, which uses the t (transpose) function.

t(ifelse(t(df1)==1,names(df1),0))
     A   B   C  
[1,] "0" "0" "C"
[2,] "0" "B" "0"
[3,] "0" "0" "0"