如何for在R中创建一个考虑两个变量的循环?
就像是:
for(i in 1:10, j in 1:10) {
if vector[j] == vector2[i]
print(variable)
else print(NA) }
Run Code Online (Sandbox Code Playgroud)
这应该给我100个输出,而不是使用
vector[i] == vector[i]
Run Code Online (Sandbox Code Playgroud)
这将产生10。
编辑:到目前为止谢谢您的帮助。这是我的实际数据:
for(i in 1:10) {
for(j in 1:10) {
if (i == j)
print(NA)
else if(st231_eq1_alg$Output[j] == st231_eq1_alg$Input[i])
print(st231_eq1_alg_f[i])
else if(st231_eq1_alg$Output[j] == st231_eq1_alg$Output[i])
print(st231_eq1_alg_inv_f[i])
else print(NA)
}
}
Run Code Online (Sandbox Code Playgroud)
有什么想法可以最好地表示这些输出吗?再次感谢。
好像你在问一个嵌套的 for 循环
for (i in 1:10){
for(j in 1:10){
...
}
}
Run Code Online (Sandbox Code Playgroud)
但我会推荐一种不同的方法
Vectors <- expand.grid(vector1 = vector1,
vector2 = vector2)
Vectors$comparison <- with(Vectors, vector1 == vector2)
Run Code Online (Sandbox Code Playgroud)
您可以使用嵌套的 for 循环来做到这一点:
for (i in 1:10) {
for (j in 1:10) {
# Your logic in here
}
}
Run Code Online (Sandbox Code Playgroud)