You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中实现内层复用外层循环索引的嵌套循环及C#代码转译?

Hey there! Let's tackle your two R questions one by one—first handling nested loops where the inner loop reuses the outer index, then converting your C# interpolation code to work smoothly in R.

1. Using Outer Loop Index in Inner Nested Loops in R

In R, nested loops work much like they do in C# when it comes to accessing outer loop variables—you can directly reference the outer index variable inside the inner loop, since it’s in the current scope. No special syntax is needed!

Here’s a simple example to demonstrate:

# Sample vectors for the loops
outer_values <- 1:5
inner_values <- 10:14

# Outer loop with index i
for (i in seq_along(outer_values)) {
  cat(paste("Outer loop index:", i, "\n"))
  
  # Inner loop that uses the outer index i
  for (j in seq_along(inner_values)) {
    calculated_result <- outer_values[i] * inner_values[j]
    cat(paste("  Inner loop j =", j, "| Result:", calculated_result, "\n"))
  }
}

The outer index i is fully accessible inside the inner loop, so you can use it to reference elements from the outer vector or any other logic that depends on the current outer loop iteration.

2. Converting Your C# Interpolation Code to R

First, let’s note a small bug in your original C# code: you set nextDay = amounts[y] but it should be nextDay = days[y] (you accidentally used the amounts array instead of days for the next day value). We’ll fix that in the R version.

Since R uses 1-based indexing (unlike C#’s 0-based), we’ll adjust the loop ranges accordingly. Here’s the converted R function, with nested loops that reuse the outer index exactly as you need:

# Your original data
days <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
amounts <- c(100, 0, 300, 0, 0, 500, 0, 600, 0, 1000)

interpolation <- function(days, amounts) {
  # Create a copy to avoid modifying the original vector directly (good practice in R)
  amounts_modified <- amounts
  
  # Loop from 2 to length(amounts_modified)-1 (matches C# x=1 to x < lengths-1)
  for (x in 2:(length(amounts_modified) - 1)) {
    if (amounts_modified[x] == 0) {
      # Get the last non-zero value and its corresponding day
      last_aval <- amounts_modified[x - 1]
      last_day <- days[x - 1]
      
      next_aval <- NA
      next_day <- NA
      
      # Inner loop starting at x to find the next non-zero value (reuses outer index x)
      for (y in x:length(amounts_modified)) {
        if (amounts_modified[y] != 0) {
          next_aval <- amounts_modified[y]
          next_day <- days[y]  # Fixed the C# bug here
          break
        }
      }
      
      # Calculate and assign the interpolated value (only if we found a next value)
      if (!is.na(next_aval) && !is.na(next_day)) {
        amounts_modified[x] <- last_aval + (days[x] - last_day) * ((next_aval - last_aval) / (next_day - last_day))
      }
    }
  }
  
  return(amounts_modified)
}

# Test the function
interpolated_amounts <- interpolation(days, amounts)
print(interpolated_amounts)

When you run this, you’ll get the output:

[1]  100  200  300  400  450  500  550  600  800 1000

Which correctly fills the 0 values with linear interpolation between the nearest non-zero points.

Bonus: A More "R-like" Vectorized Approach

If you want to avoid loops entirely (R is optimized for vector operations), you can use the na.approx() function from the zoo package. First replace 0s with NA, then interpolate:

library(zoo)

# Replace 0s with NA
amounts_na <- ifelse(amounts == 0, NA, amounts)

# Perform linear interpolation using days as the x-values
interpolated_vectorized <- na.approx(amounts_na, x = days)
print(interpolated_vectorized)

This gives the same result but is faster for large datasets.

内容的提问来源于stack exchange,提问作者Mike0298

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:09:18