2

Given the following data.frame df:

   Typ1 Typ2
    1    0         
    0    1         
    1    0  

And want to replace the values in each column where the value is set to 1 (is there a smarter possibility as the following?):

df["Typ1"][df["Typ1"] == 1]<-"Typ1"
df["Typ2"][df["Typ2"] == 1]<-"Typ2"

And merge the columns to:

   Typ 
  "Typ1"           
  "Typ2"           
  "Typ1"    
Hölderlin
  • 424
  • 1
  • 3
  • 16

2 Answers2

3
library(tidyr)
df %>% 
  pivot_longer(Typ1:Typ2, names_to = "Typ") %>% 
  filter(value == 1) %>% 
  select(Typ)

Output:

# A tibble: 3 × 1
  Typ  
  <chr>
1 Typ1 
2 Typ2 
3 Typ1 

Input:

df <- structure(list(Typ1 = c("1", "0", "1"), Typ2 = c("0", "1", "0"
)), row.names = 2:4, class = "data.frame")
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

Data:

Typ1 <- sample(rep(c(1,0),10))
Typ2 <- as.numeric(Typ1<1)
df <- data.frame(Typ1,Typ2)

Slightly more efficient indexing solution:

df$Typ <- NA
df$Typ[df$Typ2 == 1] <- "Typ2"
df$Typ[df$Typ1 == 1] <- "Typ1"
Roasty247
  • 679
  • 5
  • 20