Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
# for loop — iterate over a vector fruits <- c("apple", "banana", "cherry") for (fruit in fruits) { cat("I like", fruit, " ") } # for loop with index n <- 5 result <- numeric(n) # pre-allocate for performance for (i in seq_len(n)) { result[i] <- i ^ 2 } result # 1 4 9 16 25 # Nested for loop mat <- matrix(0, nrow = 3, ncol = 3) for (i in 1:3) { for (j in 1:3) { mat[i, j] <- i * j } } mat # multiplication table # next — skip even numbers for (i in 1:10) { if (i %% 2 == 0) next cat(i, "") } cat(" ") # 1 3 5 7 9 # break — exit early for (i in 1:100) { if (i > 5) break cat(i, "") } cat(" ") # 1 2 3 4 5 # while loop count <- 1 while (count <= 5) { cat("count =", count, " ") count <- count + 1 } # repeat loop (must contain break) x <- 1 repeat { cat(x, "") x <- x + 1 if (x > 5) break } cat(" ") # 1 2 3 4 5
Result
Open