R中基于idex的For循环
我有这个数据。frameR中基于idex的For循环,r,for-loop,R,For Loop,我有这个数据。frameA A Index col2 1 10 2 7 3 3 这个data.frameB index col2 col3 1 0.2 0.8 2 0.3 0.7 3 0.1 0.9 现在,我将计算df(A[,2])的百分比,当索引相同时,使用df(B)的col1和col2中的值。 预期产出为: C col1 col2 0.002 0.008 #
A
A
Index col2
1 10
2 7
3 3
这个data.frameB
index col2 col3
1 0.2 0.8
2 0.3 0.7
3 0.1 0.9
现在,我将计算df(A[,2])
的百分比,当索引相同时,使用df(B)
的col1和col2中的值。
预期产出为:
C
col1 col2
0.002 0.008 # A[1,2]/100*B[1,2]=0.002 & A[1,2]/100*B[1,3]=0.008 if the index is the same for the two data.frame, in this case is 1
.... ....
0.003 0.0027 #A[3,2]/100*B[3,2] & [3,2]/100*B[3,3] because the index is the same, 3 in this case.
如何使用(仅)loop for
来执行此操作,请?我们可以使用
A[,2][row(B[-1])]/100*B[-1]
您可以尝试嵌套循环:
A <- read.table(text = "
Index col2
1 10
2 7
3 3
", header = TRUE)
B <- read.table(text = "
col2 col3
0.2 0.8
0.3 0.7
0.1 0.9
", header = TRUE)
for(i in 1:3){
for(f in 1:2){
print(A[i,f]/100*B[i,f])
}
}
A数据
df_a <- data.frame(index = c(1, 2, 3), col2 = c(10, 7, 3))
df_b <- data.frame(index = c(1, 2, 3), col2 = c(.2, .3, .1), col3 = c(.8, .7, .9))
带回路
for (i in 1:nrow(df_a)) print((df_a[i, 2] / 100) * (df_b[i, 2:3]))
你因为坚持使用for
循环而没有给出(令人信服的)理由而遭到我的否决票。如果我使用for循环,我可以直接管理每个输入,例如,我可以使用自己编写的MOTE CARLO模拟…使用for
循环而不是矢量化操作来执行此操作速度很慢。对于MC模拟,您需要快速代码。您知道对于循环,我可以使用sapply吗?(基本答案不包括基于索引的操作)sapply
并不比for
循环更有效。
for (i in 1:nrow(df_a)) print((df_a[i, 2] / 100) * (df_b[i, 2:3]))