1

Please modify below code by loan id in R for below data

id     no_of_months   reminder
1        2              16
2        2              15
3        3              15
4        2              12
5        2              14

I want to apply below formula in 3rd column as no_of_months.

if(reminder > 0 & reminder < 15){
        no_of_months= no_of_months - 1
}
else{
        no_of_months
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Sona
  • 25
  • 4

1 Answers1

-1

If I interpret your question correctly, you want to create a third column that satisfies that equality.

You can use ifelse as Ronak has shown, but in keeping with for-loop form, you might want to try something like:

df <- data.frame("no_of_months" = c(2, 2, 3, 2, 2),
                 "reminder" = c(16, 15, 15, 12, 14))

for(i in 1:nrow(df)){
  if(df$reminder[i] > 0 & df$reminder[i] < 15){
        df$newColumn[i] <- df$no_of_months[i] - 1
  }else{
        df$newColumn[i] <- df$no_of_months[i]
  }
}

In this loop, we use $ to index a column of a data.frame by name. By indexing an unnamed column, we create a column. Then, we use i to index the entry in that column (equivalent to row).

Roland
  • 127,288
  • 10
  • 191
  • 288
Thom Quinn
  • 308
  • 1
  • 7
  • 2
    @Sobana This loop is slow compared to the vectorized solution. – Roland Dec 20 '16 at 08:55
  • 1
    @Roland It's a bit more complicated than that (link: http://stackoverflow.com/questions/34005423/is-if-faster-than-ifelse). Also, IMHO, relying on ifelse teaches bad fundamentals ;) – Thom Quinn Dec 20 '16 at 09:09
  • Looping over the rows of a data.frame is not a fundamental in R. Vectorization is. – Roland Dec 20 '16 at 10:51