Home > Back-end >  Problem filling a column using logical conditions in R
Problem filling a column using logical conditions in R

Time:06-03

I have a dataframe dfpp with the columns dfpp$Block, containing either "creative" or "non-creative" and dfpp$MeanOriginell, containing values between 0 and 99.

I am trying to make a new column with the labels "creative, "non-creative", and "fail".

"creative" shall be applied to all rows where dfpp$Block is "creative" AND dfpp$MeanOriginell is greater than 49.

"non-creative" shall be applied to all rows where dfpp$Block is "non-creative" AND dfpp$MeanOriginell is smaller than 49.

"fail" shall be applied to all other rows.

I have tried to do this with the following code:

dfpp$Success <- factor(ifelse(dfpp$Block=="creative" && dfpp$MeanOriginell > 49, "creative",
                                  ifelse(dfpp$Block=="non-creative" && dfpp$MeanOriginell < 49, "non-creative", "fail")),
                           levels=c("creative", "non-creative", "fail"))

This does not work as intended. Everything gets lumped into the category "fail" so that there are zero occurences of "non-creative" and "creative" in dfpp$Success.

I get the following warnings:

1: In dfpp$Block == "creative" && dfpp$MeanOriginell > 49 :
  'length(x) = 9453 > 1' in coercion to 'logical(1)'
2: In dfpp$Block == "creative" && dfpp$MeanOriginell > 49 :
  'length(x) = 9453 > 1' in coercion to 'logical(1)'
3: In dfpp$Block == "non-creative" && dfpp$MeanOriginell < 49 :
  'length(x) = 9453 > 1' in coercion to 'logical(1)'

What am I doing wrong?

CodePudding user response:

You can do it step by step.

# Initially all the values as "fail"
  dfpp$success <- "fail"
# Condition to be "creative"  
  dfpp$success[dfpp$Block=="creative" & dfpp$MeanOriginell > 49] <- "creative"
# Condition to be "non-creative"  
  dfpp$success[dfpp$Block=="non-creative" & dfpp$MeanOriginell <49] <- "non-creative"
  • Related