0

I have tree columns and I want to compute a new variable ("tot.price") as multiplications of these three variables based on conditions below:

A) if V1==1 then put value 1 in the new value "tot.price"

B) if V1==2 then multiply weight of 0.25 and multiply V2*V3 in the new value "tot.price"

C) if V1==3 then multiply weight of 0.5 and multiply V2*V3 in the new value "tot.price"

D) if V1==4 then multiply weight of 0.75 and multiply V2*V3 in the new value "tot.price"

E) if V1==5 then multiply weight of 1 and multiply V2*V3 in the new value "tot.price"

I have constructed code below but it gives me warning that " the condition has length > 1 and only the first element will be used". any help please?

if (data$V1 == "1") {
  tot.price <- 1
} else {
  if (data$V1 == "2") {
    tot.price <- 0.25 * data$V2 * data$V3
  } else {
    if (data$V1 == "3") {
      tot.price <- 0.5 * data$V2 * data$V3
    } else {
      if (data$V1 == "4") {
        tot.price <- 0.75 * data$sub1_likelihood * data$sub1_severeness
      } else {
        if (data$V1 == "5") {
          tot.price <- data$V2 * data$V3
        } else {
        }
      }
    }
  }
}
zx8754
  • 52,746
  • 12
  • 114
  • 209
ashkan
  • 113
  • 2
  • 8

1 Answers1

-1

Are you sure you want to go with nested ifs? How about:

ref=data.frame(a=seq(1:5),b=as.character(seq(1:5)))
df=data.frame(V1=as.integer(runif(20,1,6)))

df$tot.price=unlist(sapply(df$V1, function(x) ref[(abs(ref$a-x)<0.001),2]))
Antonios
  • 1,919
  • 1
  • 11
  • 18