mardi 6 février 2018

nested if functions in R

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 {
 } } } } }

Aucun commentaire:

Enregistrer un commentaire