Home > Software engineering >  Is there a function in R where I can print the only other unique element in a row?
Is there a function in R where I can print the only other unique element in a row?

Time:04-01

have a seriously confusing problem that I'd like to get help on.

I have the following data table:

type value
cat 1
dog 0
cat 1
cat 1
cat 1
dog 0

There are only two unique values in the column type. I want to mutate a new column where I search for the value 0, but then print cat, which is the only other unique value in the type column, and not dog. As so,

type value mutated
cat 1 _
dog 0 cat
cat 1 _
cat 1 _
cat 1 _
dog 0 cat

I have no clue where to start. I've tried ifelse statements but they fail to print the opposite of the value in that row. Any help?

Here's a function I've tried

data %>% mutate(mutated = ifelse(value == 0, !(type), type))

However, that just gives me an error.

CodePudding user response:

You can use the following code:

library(tidyverse)
df %>%
  mutate(mutated = ifelse(value == 0, "cat", "-"))

Output:

# A tibble: 6 × 3
  type  value mutated
  <chr> <dbl> <chr>  
1 cat       1 -      
2 dog       0 cat    
3 cat       1 -      
4 cat       1 -      
5 cat       1 -      
6 dog       0 cat 

Your data

dput(df)
structure(list(type = c("cat", "dog", "cat", "cat", "cat", "dog"
), value = c(1, 0, 1, 1, 1, 0)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L))

CodePudding user response:

You could use setdiff, which will take the difference between a vector of all type (which is length of 2, just "cat" and "dog") and the type for a given row. There are other ways to approach this depending on what you need.

library(tidyverse)

df %>%
  rowwise() %>%
  mutate(mutated = ifelse(value == 0, setdiff(unique(df$type), type), "-"))

Output

  type  value mutated
  <chr> <dbl> <chr>  
1 cat       1 -      
2 dog       0 cat    
3 cat       1 -      
4 cat       1 -      
5 cat       1 -      
6 dog       0 cat 
  • Related