简体   繁体   中英

How can I implement nested loop with inner loop using index of outer loop index as base for incrementation in R?

How do I implement in R a nested loop that has the inner loop using the outer loop index. Here is the sample of the code I wrote in C#:

int[] days = [1,2,3,4,5,6,7,8,9,10];
int[] amounts = [100, 0, 300, 0 , 0 , 500 , 0 , 600, 0, 1000];
void interpolation(int[]days, int[]amounts){
    //start with 1 to avoid amounts[0] is 0 will throw loop out of bound, same for amounts.length()-1
    for (int x = 1; x < amounts.length()-1; x++){
        if (amounts[x] == 0){
            int lastAval = amounts[x-1];
            int lastDay = days[x-1];
            int nextAval, nextDay;
            for (int y = x; y < amounts.length()-1; y++) {
                if(amounts[y] != 0) {
                    nextAval = amounts[y];
                    nextDay = amounts[y];
                    break;
                }
            }
            amounts[x] = lastAval + (days[x] - lastDay) * ((nextAval-lastAval)/(nextDay-lastDay));
        }
    }
}

The purpose of this function is to find and replace any array element that equal to 0 with interpolation. I tried to apply the same function into R and I can't seem to find a way to translate this from C# into R as I unable to find a way to iterate through the R vector and using the index from outer loop and assign it to the inner loop for iterating.

If you want to implement your linear interpolation objective in R, you can try the code below

  • Using approxfun()
# define the linear interpolation function `interpl`, using `approxfun` given non-zero value pairs
interpl <- approxfun(days[amounts!=0], amounts[amounts!=0])

then run interpl with your input days

amounts <- interpl(days)

or

amounts[amounts == 0] <- interpl(days[amounts == 0])
  • Using approx()
amount[amounts==0] <- approx(x = days[amounts!=0], 
                             y = amounts[amounts!=0],
                             xout = days[amounts==0])$y

such that

> amounts
 [1]  100.0000  200.0000  300.0000  366.6667  433.3333  500.0000  550.0000  600.0000  800.0000 1000.0000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM