x = 0 while(x < 10){ print(x) x = x + 1 if(x == 5){ print(x) break } } vec <- c(1,2,3,4,5, 6, 8, 9, 10,100) for(var in vec){ print(var) } mat <- matrix(1:25, nrow=5) print(mat) #iterate by rows for(row in 1:nrow(mat)){ for(col in 1:ncol(mat)){ print(paste('The element at row: ', row, 'and col: ', col, 'is', mat[row, col])) } } 1:nrow(mat) #Add the total for each column by iterating over each colomn total.col1 <- 0 for(col in 1:ncol(mat)){ for(row in 1:nrow(mat)){ #print(paste('The element at col: ', col, 'and row: ', row, 'is', mat[row, col])) total.col1 <- total.col1 + mat[row, col] if(row == 5){ print(paste('Total col ', col, ': ', total.col1)) total.col1 <- 0 } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter