如何用嵌套for循环生成所有变量组合并存储计算结果?
问题
需要用嵌套for循环计算两个方程x和y在两个向量上的所有可能组合,并存储每一次计算结果。现有R代码运行后仅输出对角组合,无法得到全部两两组合。
当前使用的R代码:
n_c = 1 m_c = 1 n_n = 1 m_n = 1 my_data_c = c() my_data_n = c() rho_c_store = c() rho_n_store = c() for(i in 1:10){ for(j in 1:10){ rho_c = i / 10 rho_n = j / 10 x = (rho_c*n_c)/m_c y = (rho_n*n_n)/m_n rho_c_store[i] = rho_c rho_n_store[j] = rho_n my_data_c[i] = x my_data_n[j] = y my_data = cbind(rho_c_store,rho_n_store,my_data_c,my_data_n) } } print(my_data)
当前输出(仅对角组合):
> print(my_data) rho_c_store rho_n_store my_data_c my_data_n [1,] 0.1 0.1 0.1 0.1 [2,] 0.2 0.2 0.2 0.2 [3,] 0.3 0.3 0.3 0.3 [4,] 0.4 0.4 0.4 0.4 [5,] 0.5 0.5 0.5 0.5 [6,] 0.6 0.6 0.6 0.6 [7,] 0.7 0.7 0.7 0.7 [8,] 0.8 0.8 0.8 0.8 [9,] 0.9 0.9 0.9 0.9 [10,] 1.0 1.0 1.0 1.0
期望输出(全部两两组合):
> print(my_data) rho_c_store rho_n_store my_data_c my_data_n [1,] 0.1 0.1 ? ? [2,] 0.1 0.2 ? ? [3,] 0.1 0.3 ? ? [4,] 0.1 0.4 ? ? [5,] 0.1 0.5 ? ? [6,] 0.1 0.6 ? ? [7,] 0.1 0.7 ? ? [8,] 0.1 0.8 ? ? [9,] 0.1 0.9 ? ? [10,] 0.1 1.0 ? ? [11,] 0.2 0.1 ? ? [12,] 0.2 0.2 ? ? [13,] 0.2 0.3 ? ? [14,] 0.2 0.4 ? ? [15,] 0.2 0.5 ? ? ... etc
已知可用grid.expand()和apply()实现,但希望修复当前嵌套for循环写法达成需求。
解决方案
问题根源
原代码的核心问题是用i和j作为存储向量的索引,每次循环只会覆盖对应位置的元素,而非新增行来存储所有组合。比如内层循环中rho_c_store[i] = rho_c始终只修改第i个位置的值,无法记录同一i下不同j的组合。
修改后的代码
n_c = 1 m_c = 1 n_n = 1 m_n = 1 # 预先初始化数据框,总共有10*10=100行 my_data = data.frame( rho_c_store = numeric(100), rho_n_store = numeric(100), my_data_c = numeric(100), my_data_n = numeric(100) ) row_index = 1 # 用独立的行索引来记录每一组组合的位置 for(i in 1:10){ rho_c = i / 10 x = (rho_c*n_c)/m_c for(j in 1:10){ rho_n = j / 10 y = (rho_n*n_n)/m_n # 把当前组合写入对应的行 my_data[row_index, "rho_c_store"] = rho_c my_data[row_index, "rho_n_store"] = rho_n my_data[row_index, "my_data_c"] = x my_data[row_index, "my_data_n"] = y row_index = row_index + 1 # 索引自增,准备下一行 } } print(my_data)
说明
- 预先初始化一个100行的数据框,避免动态扩展向量带来的性能问题(虽数据量小影响不大,但属于更规范的写法)。
- 使用独立的
row_index变量,每次内层循环后自增,确保每一组(i,j)组合都写入新的一行。 - 把外层循环中不变的计算(
rho_c和x)移到内层循环外,减少重复计算,提升效率。
运行后即可得到所有100组两两组合的结果,符合期望输出格式。
内容的提问来源于stack exchange,提问作者lmbradley
相关产品推荐
相关产品推荐

