I am dealing with a 2M rows DB and my if loop is taking too long. 

The data base has 3 variables : `Gift_ID`, `ind_id` and `gift_date` with data and two empty variables which I want to fill in `min` and `max`. For every different id (`ind_id`) I want to identify the first gift date and the last gift date. I've written these two loops that worked (the loops work if the DB is ordered by `ind_ID` and then `gift_date`), but when I run them with the hole DB it takes too long. Any ideas of another way of writing this?

```
for (i in 2:length(NewGifts[,1])){
  if(NewGifts$ind_id[i] != NewGifts$ind_id[i-1]){
NewGifts$min[i] = format.Date(NewGifts$gift_date[i], '%Y%m%d')
  } else {
    NewGifts$min[i] = NewGifts$min[i-1]
  }
}

for (i in ((length(NewGifts[,1])-1):1)){
  if(NewGifts$ind_id[i] != NewGifts$ind_id[i+1]){
    NewGifts$max[i] = format.Date(NewGifts$gift_date[i], '%Y%m%d')
  } else {
NewGifts$max[i] = NewGifts$max[i+1]
  }
}

```

Maybe working with data.table is more efficient, but I couldn't find any post helping.

Sample of the data:

```
ind_id   gift_id   gift_date  
1        1         20190101 
1        2         20190102 
1        3         20190103 
1        4         20190104 
2        5         20190201 
2        6         20190319 
2        7         20190412 
2        8         20190511 
2        9         20190601 

```

Expected result :

```
ind_id   gift_id   gift_date    min         max  
1        1         20190101     20190101    20190104
1        2         20190102     20190101    20190104
1        3         20190103     20190101    20190104
1        4         20190104     20190101    20190104
2        5         20190201     20190201    20190601 
2        6         20190319     20190201    20190601 
2        7         20190412     20190201    20190601 
2        8         20190511     20190201    20190601 
2        9         20190601     20190201    20190601 

```