0

in data frame ad2, if cost values is between upper & lower, then make a new data frame. I tried the following:

if (ad2$Cost.x>=ad2$lower & ad2$Cost.x<=ad2$upper) {
  ad3<-ad2[ad2$Country,ad2$Brand, ad2$Year, ad2$BU219.x, ad2$Cost.x, ad2$Value.x, ad2$Optimized_point.x]
}

but this error comes up

  the condition has length > 1 and only the first element will be used
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22
  • If your goal is to create a new `data.frame` containing rows where the cost values is between upper & lower, you may want to try `ind <- which(ad2$Cost.x>=ad2$lower & ad2$Cost.x<=ad2$upper); ad3 <- ad2[ind, ]` – MRau Jan 18 '19 at 11:34
  • no need to use which in that case, ad3 <- ad2[ad2$Cost.x>=ad2$lower & ad2$Cost.x<=ad2$upper, ] would do. – JineshEP Jan 18 '19 at 11:39

2 Answers2

0

If you print the values of ad2$Cost.x>=ad2$lower & ad2$Cost.x<=ad2$upper, u can see more than one boolean conditions as a result. This is becuase in R all operations are vectorised.

Example:

> cc =c(T,F)
> if (cc) print(cc)
[1]  TRUE FALSE
Warning message:
In if (cc) print(cc) :
  the condition has length > 1 and only the first element will be used

So use all or any function like this :

> if (all(cc)) print(cc) #If all conditions are true
> if (any(cc)) print(cc)
[1]  TRUE FALSE
JineshEP
  • 738
  • 4
  • 7
0

Try this once

if (ad2$Cost.x>=ad2$lower & ad2$Cost.x<=ad2$upper) { ad3 <- ad2[ , c(Country,Brand, Year, BU219.x, Cost.x, Value.x, Optimized_point.x)] }

Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22