如何使用 for - R 循环在向量中查找一系列数字

问题描述 投票:0回答:1

我正在尝试找到一种方法来检查向量中是否存在一系列数字。

我正在研究数据框中的相关性,并且使用“for”循环来绘制所有变量对。然而,我试图找到一种方法来避免每对被绘制两次。我的想法是创建每列索引的序列,将它们存储在向量中,以便在每个绘图之前检查该系列是否已存在于向量中,并命令循环跳过它(如果存在)。

我想要的一个例子:

假设我在数据帧“DATA”中有以下变量:

变量1 变量2 变量3 变量4
0 1 0 4
2 3 2 5
5 4 5 0
2 5 1 1

我想根据每个变量绘制每个变量,但如果我做一个循环,我最终会得到每对两次,如下例所示:


for (i in 1:4){
  for (j in 1:4){
      if (j == i){
      next
    }
      plot(x = DATA[,i],
         y = DATA[,j],
         xlab = colnames(DATA)[i],
         ylab = colnames(DATA)[j])
  }
}

这个例子会给我两次每对变量,一次用 Var1 作为 x,Var2 作为 y,第二次用 Var1 作为 y,Var2 作为 x,对于每对变量依此类推。

我想避免这种情况,因为我的原始数据框中有几十个变量。因此,我想创建一系列具有两个索引的数字,以存储在每个循环开始时搜索的向量中,如果找到该系列,则循环跳到下一次迭代。

我尝试了以下方法,但没有成功:

vector_test <- c(0)

for (i in 1:4){
  for (j in 1:4){
      test1 <- c(0,i,j,0)
      test2 <- c(0,j,i,0) #to have both orders possible
      if (j == i){
          next
       }
       if (test1 %in% vector_test){
          next
       }
       if (test2 %in% vector_test){
          next
       }
       vector_test <- c(vector_test, test1, test2) #adding to the test vector to check in the next iteration
        plot(x = Data_total_VF[,i],
             y = Data_total_VF[,j],
             xlab = colnames(Data_total_VF)[i],
             ylab = colnames(Data_total_VF)[j])
      }
    }

我在“测试”的末尾和开头添加了 0,以避免由于两个数字在向量中随机相邻而导致跳过。

我也尝试过:

if ((test1 %in% vector_test) == TRUE{
          next
       }

两次给我的错误是:

Error in if (test1 %in% vector_test) { : the condition has length > 1

Error in if ((test1 %in% vector_test) == TRUE) { : 
  the condition has length > 1

我一直无法找到其他运营商或本网站中的另一个示例来执行此操作。

有人有想法吗?

非常感谢。

r for-loop vector series
1个回答
0
投票

使用

combn

combns <- combn(1:4, 2, simplify = FALSE)

for (ij in combns){
  i <- ij[[1]]
  j <- ij[[2]]
  plot(x = DATA[,i],
       y = DATA[,j],
       xlab = colnames(DATA)[i],
       ylab = colnames(DATA)[j])
}
© www.soinside.com 2019 - 2024. All rights reserved.