1

I have a dataframe h3

Genotype Preference
Rice     1
Rice     2
Lr       3
Lr       3
th       4
th       7

I want the dataframe to look like

Genotype Preference Haplotype
Rice     1          1
Rice     2          1
Lr       3          2
Lr       3          2
th       4          0.5
th       7          0.5

That is I want to add a numerical variable to be added to the each type of genotype. I have around 100 observations for each type of genotype. I want to be able to add the numberical variable into a new column in a single line of code and ensure that 1 is added corresponding to rice, 2 to Lr and 0.5 to th.

I tried constructing the code with the mutate/ifelse:

h3 %>% select(Genotype) %>% mutate(Type = ifelse (Genotype = c("Rice"), 1, Genotype))

Other results which I looked up, provide solutions for adding a column with a calculated value from the previous columns but not specific values.

I have found this dplyr mutate with conditional values and Apply R-function to rows depending on value in other column but dont know how to modify it for my code.

Any help with this will be greatly appreciated.

  • 2
    `=` is for assignment, `==` is for testing equality. You've tried to assign within `ifelse` instead of testing equality – camille Dec 03 '19 at 17:57
  • Thank you @camille how do I construct my code now then? because if I use == then I am getting a result which is only consisting of my genotype. I am pretty new to r. – Keerthi Krutha Dec 03 '19 at 18:14
  • 1
    Not sure what you mean. But `ifelse(Genotype = c("Rice"), 1, Genotype))` should be `ifelse(Genotype == "Rice", 1, Genotype))`, if what you want is to replace "Rice" with 1 – camille Dec 03 '19 at 18:29

1 Answers1

2

Using dplyr, you can do:

library(dplyr)
df %>% mutate(Haplotype = ifelse(Genotype == "Rice",1,ifelse(Genotype == "Lr",2,0.5)))

Using base, you can do the same thing:

df$Haplotype = ifelse(df$Genotype == "Rice",1,ifelse(df$Genotype == "Lr",2,0.5))

Data

df = data.frame("Genotype" = c("Rice","Rice","Lr","Lr","Th","Th"),
                "Preference" = c(1,2,3,3,4,7))  
dc37
  • 15,840
  • 4
  • 15
  • 32
  • 1
    @KeerthiKrutha, glad that it works for you. FYI, `ifelse` structure is 1st argument is the condition to be tested, 2nd argument is the output if the 1st argument is True, 3rd argument is the output if the 1st argument is False. – dc37 Dec 03 '19 at 19:01