lukitamodric
lukitamodric

Reputation: 37

How to create a new column based on different columns in dplyr

If I have a the following df

id tiger donkey turtle
1 1 0 0
2 0 1 0
3 0 0 1

So that 1 equals True and 0 equals False.

And I want to create the following df

id animal
1 tiger
2 donkey
3 turtle

How would I do this using dplyr? I first thought that I could use pivot_long() but I should not have more rows after the operation.

Upvotes: 0

Views: 196

Answers (2)

erget89795
erget89795

Reputation: 11

A possibility with dplyr :

id = c(1,2,3)
tiger = c( 1,0,0)
donkey = c(0,1,0)
turtle = c(0,0,1)

original_df = data.frame(id,tiger,donkey,turtle)

library(dplyr)

original_df %>% mutate(animal = case_when(tiger==1~"tiger", donkey==1~"donkey", 
turtle==1~"turtle")) %>% select(id,animal)

Upvotes: 1

r2evans
r2evans

Reputation: 161110

dplyr

library(dplyr)
library(tidyr) # pivot_longer
pivot_longer(dat, -id, names_to = "animal") %>%
  filter(value > 0)
# # A tibble: 3 x 3
#      id animal value
#   <int> <chr>  <int>
# 1     1 tiger      1
# 2     2 donkey     1
# 3     3 turtle     1

base plus reshape2

subset(
  reshape2::melt(dat, id.vars = "id", variable.name = "animal"),
  value > 0)

Upvotes: 2

Related Questions