0

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?

Laura
  • 177
  • 1
  • 12

1 Answers1

0
agg<-data.frame(division=c(45,46,47),agg_4546=c(10,11,NA),agg_47=c(NA,NA,10))

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

you missed the double "==" in the if condition and the "[row]" to adress to the specific entry not to the full column of "agg"

Triss
  • 561
  • 3
  • 11