- R Data Visualization Cookbook
- Atmajitsinh Gohil
- 149字
- 2021-08-06 19:21:08
Nested loops in R
We can nest loops, as well as if
statements, to perform some more complicated tasks. In this recipe, we will first define a square matrix and then write a nested for loop to print only those values where I = J, namely, the values in the matrix placed in (1,1), (2,2), and so on.
How to do it…
We first define a matrix in R using the following matrix()
function:
mat= matrix(1:25, 5,5)
Now, we use the following code to output only those elements where I = J:
for (i in 1:5){ for (j in 1:5){ if (i ==j){ print(mat[i,j]) } } }
The if
statement is nested inside two for
loop statements. As we have a matrix, we have to use two for
loops instead of just one. The output of the matrix would be values such as 1, 7, 13, and 19.
推薦閱讀
- The Complete Rust Programming Reference Guide
- 少兒人工智能趣味入門:Scratch 3.0動畫與游戲編程
- C語言程序設計實踐教程(第2版)
- Photoshop智能手機APP UI設計之道
- Groovy for Domain:specific Languages(Second Edition)
- Eclipse Plug-in Development:Beginner's Guide(Second Edition)
- JavaScript入門經典
- Clojure Reactive Programming
- Android系統原理及開發要點詳解
- Nginx Lua開發實戰
- Python+Tableau數據可視化之美
- Kubernetes源碼剖析
- Arduino Wearable Projects
- Java EE 7 with GlassFish 4 Application Server
- SEO教程:搜索引擎優化入門與進階(第3版)