0

Say I have a data frame like below:

df <- data.frame(x1=c(1,0,0,0),x2=c(0,1,0,0),x3=c(0,0,0,1),x4=c(0,0,1,0))

How can I make a new column with the title name based on if the certain row is equal to 1? So the new data frame would look like:

df2 <- data.frame(x1=c(1,0,0,0),x2=c(0,1,0,0),x3=c(0,0,0,1),x4=c(0,0,1,0),name=c(x1,x2,x4,x3))

MAJ
  • 437
  • 5
  • 17
  • 2
    [Any of these methods should work](https://stackoverflow.com/q/17735859/903061). You can also search for "convert dummy variables to factor" for plenty of similar questions. – Gregor Thomas Sep 08 '22 at 14:52

1 Answers1

1

You can use max.col:

df$name <- colnames(df)[max.col(df == 1)]
  x1 x2 x3 x4 name
1  1  0  0  0   x1
2  0  1  0  0   x2
3  0  0  0  1   x4
4  0  0  1  0   x3
Maël
  • 45,206
  • 3
  • 29
  • 67