-3

I have to create a loop but I don't know how to order to R what I want to do.

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)

How I have to finish the loop?

Thanks in advance, I'm a bit confused

Caro
  • 113
  • 1
  • 4
  • In R, you're usually better off using vectorization rather than for loops, especially once you need to start nesting loops. Here's a good article on it: https://bookdown.org/rdpeng/rprogdatascience/vectorized-operations.html – camille May 09 '18 at 12:01

2 Answers2

2

So this is a basic for-loop, which just prints out the values.

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

If you want to save the output you have to initialize a vector / list /matrix, etc.:

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

And a little example for nested loops:

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"))
    }
  }
}

But as already mentioned, you would probably be better of using an "apply"-function (apply, sapply, lapply, etc). Check out this post: Apply-Family

Or using the package dplyr with the pipe (%>%) operator.

To include some if/else-synthax in the loop:

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"))
    }
  }
}

In the first loop, I am asking if i is 1. If yes, the first print statement is used ("i is 1"), otherwise the second is used ("i is not 1").

SeGa
  • 9,454
  • 3
  • 31
  • 70
  • You could add the basic `if(condition){then-operation}` syntax, as the OP seems to have difficulty with it. +1 anyway. – LAP May 09 '18 at 12:27
0

R Repeat loop Statements R While loop executes a set of statements repeatedly in a loop as long as the condition is satisfied. We shall learn about the syntax, execution flow of while loop with R example scripts

Reference Site