Is there anyway to recode the data in one column based of a second column.
Month | Treatment |
---|---|
June | A |
May | A |
May | B |
June | B |
May | C |
June | C |
I have data for both may and june for different treatments as shown above. I was recoding the treatment column as shown below.
Treat <- recode(Flower$Treatment, A = "Mown May and June")
Treat <- recode(Treat, B = "Mown May and June")
Treat <- recode(Treat, C = "Mown May")
however I would like to recode it so that the A, May is labelled Mown May and A, June is Mown may and june. B, A is labelled Mown May and B, June is Mown may and june. And C, May is labelled Mown May and C, June is labelled Not mown.
Is there anyway to do this using the recode function as I have already.
I would like the output to look like this:
Month | Treatment | Treatment2 |
---|---|---|
June | A | Mown May and June |
May | A | Mown May |
May | B | Mown May |
June | B | Mown May and June |
May | C | No Mow May |
June | C | Mown June |
CodePudding user response:
This should work, supposing df your dataframe and no other modalities of Treatment :
df$Treatment=ifelse(df$Month=="May","Mown May",
ifelse(df$Treatment=="C","Not mown","Mown May and June"))
CodePudding user response:
If you are not restricted to recode
, you could try to use case_when()
, e.g.
df %>%
mutate(Treatment2 = case_when(
Month == "June" & Treatment %in% c("A", "B") ~ "Mown May and June",
Month == "May" & Treatment %in% c("A", "B") ~ "Mown May",
Month == "May" & Treatment == "C" ~ "No Mow May",
TRUE ~ "Mown June"
))
Result:
Month Treatment Treatment2
1 June A Mown May and June
2 May A Mown May
3 May B Mown May
4 June B Mown May and June
5 May C No Mow May
6 June C Mown June