mardi 9 mars 2021

Using if- else if - else statement to generate additional variables in R [duplicate]

I want to add two new variables a and b to dataframe m conditioned on id. How I can do this?

m <- data.frame(id=c(1,1,2,2,3,3),
                v1=c(1,2,2,3,3,5),
                v2=c(6,7,8,9,4,5))
if(m$id==1){
  m$a <- m$v1*m$v2
  m$b <- m$v1/m$v2
} else if(m$id==2){
  m$a <- m$v1-m$v2
  m$b <- m$v1+m$v2
} else
  m$a <- m$v1
  m$b <- m$v2

I'm getting an error which says the condition has length > 1 and only the first element will be used. Any help is appreciated!

Aucun commentaire:

Enregistrer un commentaire