简体   繁体   中英

How do I do a loop using R

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM