'Is there a function in R where I can print the only other unique element in a row?
I 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.
Solution 1:[1]
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
Solution 2:[2]
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
| Solution 2 | Quinten |
