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"    
0

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

Comments

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"

2 Comments

This is what the OP wants to avoid
I don't think they said they want to avoid indexing. Just "Is there a smarter possibilty", this only uses 1 set of [ ] rather than 3 sets of [ ] in OP ...so an improvement no?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.