- 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.
推薦閱讀
- Python 3.7網絡爬蟲快速入門
- HTML5 移動Web開發從入門到精通(微課精編版)
- DevOps入門與實踐
- Redis Essentials
- JavaScript 程序設計案例教程
- 程序設計基礎教程:C語言
- Node.js全程實例
- 軟件品質之完美管理:實戰經典
- Serverless Web Applications with React and Firebase
- 零基礎看圖學ScratchJr:少兒趣味編程(全彩大字版)
- 從零開始:C語言快速入門教程
- Python應用開發技術
- ASP.NET Core and Angular 2
- Practical Responsive Typography
- GO語言編程從入門到實踐