vendredi 5 février 2016

Replace a value in a dataframe with a value in another column, based on a condition on a third column

I found a lot of questions that have a similar-looking title, yet most of them have answers contextual to the problem, that don't really help solve a more general case. Sorry if there is one that answers my problem accurately and I've missed it.

I'm trying to do the following :

if (my_df$class== "foo"){
  my_df$columnB <- my_df$columnA * 2
}else{
  if (my_df$class == "bar"){
    my_df$columnB <- my_df$columnA * 5
  }else{
    my_df$columnB <- my_df$columnA * 10
  }
}

As it doesn't work, let me state it in pseudo-code :

for each row, 
    if the value in column class is "foo"
         set the value in column B to be 2 times the value in column A
    if the value in column class is "bar"
         set the value in column B to be 5 times the value in column A
    if the value in column class is something else
         set the value in column B to be 10 times the value in column A

My problem is, of course, with the assigning operator : if I use <- the whole columnB column ends up being columnA multiplied by 5 (because it so happens that the class value of the last row is bar).

Any solution ?

I'll take a solution that solves my problem without going through this if/elseif/else syntax, but I'd also really appreciate it if someone could provide a solution keeping this syntax, for the sake of learning.

Thanks

Aucun commentaire:

Enregistrer un commentaire