问题
I have a dataframe listing 400 Products. Each of these Products belong to a certain category: BODY CLEANSING, HAIR, DEO, HAND BODY, FACE, MEN, LIP, SUN and FEMALE SHAVE. Furthermore I have the Sales Month, in which each of the 400 Products were launched.
I want to create a new column in my dataframe displaying TRUE
if the product was launched in high season and FALSE
if not.
The logic is something like this:
If a product in the cateogry BODY CLEANSING or HAIR or DEO or HAND BODY or FACE or MEN or LIP was launched in the months of October or November or December high season = TRUE
and if a product in the category SUN or FEMALE SHAVE is launched in the months of either April, May, June or July high season = TRUE
.
I have tried the following:
Sample_15$high_season <- (Sample_15$Category == "BODY CLEANSING" | "HAIR"
| "DEO" | "HAND BODY"| "FACE" | "MEN" | "LIP" & Sample_15$Months_extract
== "Oktober" | "November" | "Dezember") | (Sample_15$Category == "SUN" |
"FEMALE SHAVE" & Sample_15$Months_extract == "April" |
"Mai" | "Juni" | "Juli")
And I get this Error message:
Error in Sample_15$Category == "BODY CLEANSING" | "HAIR" :
operations are possible only for numeric, logical or complex types
Does anybody know how to code the logic of the Boolean? Any help is appreciated!!!!
回答1:
Sample_15$Category == "BODY CLEANSING" | Sample_15$Category == "HAIR"
... and so on
or
Sample_15$Category %in% c("BODY CLEANSING","HAIR",...)
回答2:
Your mistake is that you don't write again the vector font of all conditions as user2974951 showed you. In your case it is easier to check if an element is inside a vector.
In term of solution, an easy way to solve this is to use dplyr
and case_when
:
Sample15 %>%
mutate(high_season = case_when(
Category %in% c("BODY CLEANSING","HAIR", "DEO","HAND BODY","FACE","MEN","LIP")
& Months_extract %in% c("Oktober","November" ,"Dezember") ~ TRUE,
Category %in% c("SUN" ,"FEMALE SHAVE")
& Months_extract %in% c("April","Mai","Juni", "Juli") ~ TRUE)) %>%
mutate(high_season = ifelse(highseason == TRUE, TRUE, FALSE)) #add FALSE to rest
With base R (not tidy)
hsm <- which(Sample15$Category %in% c("BODY CLEANSING","HAIR", "DEO","HAND BODY","FACE","MEN","LIP")
& Sample15$Months_extract %in% c("Oktober","November" ,"Dezember"))
Sample15[hsm,high_season] <- TRUE
hsf <- which(Sample15$Category %in% c("SUN" ,"FEMALE SHAVE")
& Sample15$Months_extract %in% c("April","Mai","Juni", "Juli"))
Sample15[hsf,high_season] <- TRUE
Sample15$highseason <- ifelse(Sample15$high_season == TRUE, TRUE, FALSE)
来源:https://stackoverflow.com/questions/57753892/r-combine-various-logical-operators-within-boolean-or-if-statements