1

Im trying to create a new character variable (in my example V4) based on values of other variables. I need to use the column names to fill this new variable.

I have this:

  V1 V2 V3
1  1  0  1
2  0  1  1
3  0  0  0
4  1  1  1

And i hope the new variable contains all the column names where the value are equal to 1

Like this:

V1 V2 V3       V4
1  1  0  1    "V1,V3"
2  0  1  1    "V2,V3"
3  0  0  0     " " 
4  1  1  1   "V1,V2,V3"

example data:

data.frame(
   V1 =c(1,0,0,1),
   V2 = c(0,1,0,1),
   V3 = c(1,1,0,1)
)
Lucca Nielsen
  • 1,497
  • 3
  • 16

2 Answers2

3

You can use the following code:

library(dplyr)
df %>%
  rowwise() %>%
  mutate(V4 = paste0(names(.)[c_across() == 1], collapse = ','))

Output:

# A tibble: 4 × 4
# Rowwise: 
     V1    V2    V3 V4        
  <dbl> <dbl> <dbl> <chr>     
1     1     0     1 "V1,V3"   
2     0     1     1 "V2,V3"   
3     0     0     0 ""        
4     1     1     1 "V1,V2,V3"

Data

df <- data.frame(
  V1 = c(1,0,0,1),
  V2 = c(0,1,0,1),
  V3 = c(1,1,0,1)
)
Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Your solution is filling the new variable with NA,NA,NA when the value isnt equal to 1. How can i just fill with the names of columns with value equal to 1? – Lucca Nielsen Jun 02 '22 at 12:47
  • @LuccaNielsen, I used exactly your data and it produces exactly your desired output. When there are no 1 in a row, it does not return as NA but just as "". – Quinten Jun 02 '22 at 12:52
  • Could you please share the code you used and output with that code? – Quinten Jun 02 '22 at 12:53
3

Using base R with apply

df1$V4 <- apply(df1, 1, \(x) toString(names(x)[x ==1]))
akrun
  • 874,273
  • 37
  • 540
  • 662