mercredi 25 mars 2020

How do I loop an operation over rows, depending on a column value? R

I'm trying to create a new column sep_l_values which depends on the value in a column division.

I have some data agg

division   agg_4546   agg_47  
  45         10         NA     
  46         11         NA   
  47         NA         10   

I want:

division   agg_4546   agg_47  sep_l
  45         10         NA     10
  46         11         NA     11
  47         NA         10     10

Why doesn't this work? Please can you provide a solution?

for (row in 1:nrow(agg)){
  if (agg[row,'division'] = 47){
    agg$sep_l <- agg$agg_47
  } else {
    agg$sep_l <- agg$agg_4546 
  }
}

The error message says

Error: unexpected '=' in:
"for (row in 1:nrow(div_to_agg)){
  if (div_to_agg[row,'division'] ="

But I require the = for the condition?

Aucun commentaire:

Enregistrer un commentaire