首页 > 解决方案 > 如何使用 R 进行循环

问题描述

我必须创建一个循环,但我不知道如何订购 R 我想做的事情。

for(i in 1:nrow(File1))
  for(j in 1:ncol(File2)){
    if [(x(i,1)==(cd(1,j)))] # Until here I think it is ok
             THEN            # I don't know what is the command for THEN in R
      for (k in File3) #I have to take all the data appearing in File3

Output (k,1)= K # I don't know what is the command to order the output in R
Output (k,2)= cd(1,j)
Output (k,3)= x(i,2)
Output (k,4)= x(i,3)
Output (k,5)= x(i,4)
Output (k,6)= cd(1,j)

我必须如何完成循环?

提前谢谢,我有点困惑

标签: rloops

解决方案


所以这是一个基本的 for 循环,它只是打印出值。

data <- cbind(1:10); 
for (i in 1:nrow(data)) {
  print(i)
}

如果要保存输出,则必须初始化向量/列表/矩阵等:

output <- vector()
for (i in 1:nrow(data)) {
  k[i] <- i
}
k

还有一个嵌套循环的小例子:

data <- cbind(1:5); 
data1 <- cbind(15:20)
data2 <- cbind(25:30)
for (i in 1:nrow(data)) {
  print(paste("FOR 1: ", i))
  for (j in 1:nrow(data1)) {
    print(paste("FOR 2: ", j))
    for (k in 1:nrow(data2)) {
      cat(paste("FOR 3: ", k, "\n"))
    }
  }
}

但正如已经提到的,您可能会更好地使用“应用”功能(应用、sapply、lapply 等)。看看这篇文章:申请家庭

或者将包 dplyr 与管道 (%>%) 运算符一起使用。

在循环中包含一些 if/else-synthax:

data <- cbind(1:5); 
data1 <- cbind(15:20)
data2 <- cbind(25:30)

for (i in 1:nrow(data)) {
  if (i == 1) {
    print("i is 1")
  } else {
    print("i is not 1")
  }
  for (j in 1:nrow(data1)) {
    print(paste("FOR 2: ", j))
    for (k in 1:nrow(data2)) {
      cat(paste("FOR 3: ", k, "\n"))
    }
  }
}

在第一个循环中,我询问 i 是否为 1。如果是,则使用第一个 print 语句(“i is 1”),否则使用第二个(“i is not 1”)。


推荐阅读