samedi 11 juillet 2020

How to filter and group the data based on specific conditions in R?

I want to filter and group the data of my df according to the character in the comment_1 and comment_2 and give the indicator 0 or 1 as a final result. However, there are some rules that come together with the filter. The rules are:

  1. If the comment_1 of the row consists of apple and the comment_2 of the row consists of apple as well, then use price_1 minus price_2. If the number after subtraction is greater than 20, then the result will be 1, if less than 20, then the result will be 0

  2. If the comment_1 of the row consists of orange and comment_2 consists of apple / the comment_1 consist of apple and comment_2 consist of orange, then also use price_1 minus price_2. If the number after sbutraction is greater than 10, then the result wil be 1 otherwise the result will be 0.

Take note that the it doesn't matter is Apple or apple, Orange or orange, so the code should take capital letter into consideration as well.

For example:

  1. 1st row of the data is apple (comment_1) to Apple (comment_2), and the result of price_1 minus price_2 is 13 which is smaller than 20, hence the result will be shown as 0.

  2. 2nd row of the data is orange (comment_1) to Apple (comment_2) and the result is 11 after minus price_1 with price_2, since 11 is greater than 10, so the final result will be shown as 1.

  3. Since the 4th row price_1 - price_2 = 2 which is smaller than 10, so the result is 0.

I attached my df as below and the final column result is the final answer. Appreciate your help!

price_1 <- c(25, 33, 54, 24)
price_2 <- c(12, 22, 11, 22)
itemid <- c(22203, 44412,55364, 552115)
itembds <- as.integer(c("", 21344, "", ""))
comment_1 <- c("The apple is expensive", "The orange is sweet", "The Apple is nice", "the apple is not nice")
comment_2 <- c("23 The Apple was beside me", "The Apple was left behind", "The apple had rotten", "the Orange should be fine" )
result <- c(0, 1, 1, 0)

df <- data.frame(price_1, price_2, itemid, itembds, comment_1, comment_2, result)

enter image description here

Aucun commentaire:

Enregistrer un commentaire