lundi 2 septembre 2019

R: How to combine several conditions with logical operators for a Boolean vector or if statement

I have the following dataframe:

Category <- rep(c("FACE", "LIP", "BODY", "HAIR", "SUN"), each = 2)
Month <- c("October", "Janurary", "April", "Feburary", "November", 
"August", "October", "May", "June", "December")
df2 <- data.frame(Category, Month)

  Category    Month
1      FACE  Oktober
2      FACE Janurary
3       LIP    April
4       LIP Feburary
5      BODY November
6      BODY   August
7      HAIR  October
8      HAIR      May
9       SUN     June
10      SUN December

I want to add another column "high season" = TRUE if Category FACE, LIP, BODY or HAIR are in Month Oktober, November or December and if Category SUN is in April, May, June or July.

The result should thus look like this:

   Category    Month high_season_result
1      FACE  October               TURE
2      FACE Janurary              FALSE
3       LIP    April              FALSE
4       LIP Feburary              FALSE
5      BODY November               TURE
6      BODY   August              FALSE
7      HAIR  October               TRUE
8      HAIR      May              FALSE
9       SUN     June               TRUE
10      SUN December              FALSE

I have tried this code:

df2$high_season <- (df2$Category == "FACE" & ((df2$Month == "October") | 
(df2$Month == "November") | (df2$Month == "December"))) | (df2$Month == 
"BODY" & ((df2$Month == "October") | (df2$Month == "November") |                       
(df2$Month == "December"))) | (df2$Category == "LIP" &                                                       
((df2$Month == "October") |                                                            
(df2$Month == "November") |                                                            
(df2$Month == "December"))) | 
  (df2$Category == "HAIR" & ((df2$Month == "October") | (df2$Month == 
November") | (df2$Month == "December"))) | (df2$Month == "SUN" &                                                              
((df2$Month == "April") |                                               
(df2$Month == "May") |                                                             
(df2$Month == "June") |                                                               
(df2$Month == "July")))

The Boolean gets messed up:

   Category    Month high_season
1      FACE  October        TRUE
2      FACE Janurary       FALSE
3       LIP    April       FALSE
4       LIP Feburary       FALSE
5      BODY November       FALSE
6      BODY   August       FALSE
7      HAIR  October        TRUE
8      HAIR      May       FALSE
9       SUN     June       FALSE
10      SUN December       FALSE

I have tried to remove brackets in the code, the Boolean changes then but still it is not the correct result. I suspect that I am messing it up with the brackets or with the logical operators.

Can someone help?

Aucun commentaire:

Enregistrer un commentaire