ana_gg
ana_gg

Reputation: 370

Why r shows an error when using dplyr and ifelse together?

I am trying to use the "ifelse" function in R grouping but it doesn't work. My data is something like this:

Breed Animal
NOR    1  
NOR    1
SWE    1
HOL    2
NOR    2
NOR    3
NOR    3

So I want to create a new variable, called "comp" for composition in which if the breed for the animal is always NOR, it is purebred, if not, it is admixed. The data.frame is called NOR and the code I used is:

NOR %>%
group_by (animal) %>%%
mutate(comp= ifelse(NOR$breed == "NOR", "purebred","admixed")

But then I have this error: Error: Column 'comp' must be length 28 (the group size) or one, not 1104.

The output that I need is:

Breed Animal comp  
NOR     1     admixed
NOR     1     admixed
SWE     1     admixed
HOL     2     admixed
NOR     2     admixed
NOR     3     purebred
NOR     3     pubebred

Thank you in advance! :)

Upvotes: 1

Views: 110

Answers (2)

akrun
akrun

Reputation: 886948

In this case, we can use if/else as the input is a single TRUE/FALSE value

library(dplyr)
df %>%
     group_by(Animal) %>% 
     mutate(comp = if(all(Breed == "NOR")) "purebred" else "admixed")
# A tibble: 7 x 3
# Groups:   Animal [3]
#  Breed Animal comp    
#  <chr>  <dbl> <chr>   
#1 NOR        1 admixed 
#2 NOR        1 admixed 
#3 SWE        1 admixed 
#4 HOL        2 admixed 
#5 NOR        2 admixed 
#6 NOR        3 purebred
#7 NOR        3 purebred

data

df <- structure(list(Breed = c("NOR", "NOR", "SWE", "HOL", "NOR", "NOR", 
"NOR"), Animal = c(1, 1, 1, 2, 2, 3, 3)), row.names = c(NA, -7L
), class = c("tbl_df", "tbl", "data.frame"))

Upvotes: 1

rpolicastro
rpolicastro

Reputation: 1305

Example data.

df <- tibble(
   "Breed" = c(rep("NOR", 2), "SWE", "HOL", rep("NOR", 3)),
   "Animal" = c(rep(1, 3), rep(2, 2), rep(3, 2))
)

> df
# A tibble: 7 x 2
  Breed Animal
  <chr>  <dbl>
1 NOR        1
2 NOR        1
3 SWE        1
4 HOL        2
5 NOR        2
6 NOR        3
7 NOR        3

Instead of 'NOR$breed', you want to have just 'Breed'. You also want to wrap the condition in 'all'.

df %>%
   group_by(Animal) %>%
   mutate(comp = ifelse(all(Breed == "NOR"), "purebred", "admixed"))

# A tibble: 7 x 3
# Groups:   Animal [3]
  Breed Animal comp    
  <chr>  <dbl> <chr>   
1 NOR        1 admixed 
2 NOR        1 admixed 
3 SWE        1 admixed 
4 HOL        2 admixed 
5 NOR        2 admixed 
6 NOR        3 purebred
7 NOR        3 purebred

Upvotes: 2

Related Questions