Home > OS >  Create new column containing names of other columns based on values ​of those columns
Create new column containing names of other columns based on values ​of those columns

Time:06-02

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)
)

CodePudding user response:

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"

CodePudding user response:

Using base R with apply

df1$V4 <- apply(df1, 1, \(x) toString(names(x)[x ==1]))
  • Related