- 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.
推薦閱讀
- TypeScript Essentials
- Python科學(xué)計算(第2版)
- PaaS程序設(shè)計
- 深入實踐Spring Boot
- Raspberry Pi for Secret Agents(Third Edition)
- Learning Elixir
- JS全書:JavaScript Web前端開發(fā)指南
- Python圖形化編程(微課版)
- 打開Go語言之門:入門、實戰(zhàn)與進階
- Kubernetes進階實戰(zhàn)
- Go語言入門經(jīng)典
- 實戰(zhàn)Python網(wǎng)絡(luò)爬蟲
- 分布式系統(tǒng)架構(gòu)與開發(fā):技術(shù)原理與面試題解析
- 人件集:人性化的軟件開發(fā)
- Splunk Developer's Guide(Second Edition)