Skip to Content
R 语言经典实例(原书第 2 版)
book

R 语言经典实例(原书第 2 版)

by J.D. Long, Paul Teetor
June 2020
Beginner to intermediate
522 pages
9h 6m
Chinese
China Machine Press
Content preview from R 语言经典实例(原书第 2 版)
简单编程
459
15.1.4 另请参阅
这里介绍的 if 结构用于编程。还有一个名为 ifelse 的函数实现了一个向量化的 if/
else 结构,对于转换整个向量很有用。请参阅 help(ifelse)
15.2 用循环进行迭代
15.2.1 问题
需要循环迭代向量或列表的元素。
15.2.2 解决方案
常见的迭代技术使用 for 结构。如果 v 是向量或列表,则此 for 循环逐个选择 v 的每
个元素,将元素分配给 x,并对其执行某些操作:
for (x in v) {
# do something with x
}
15.2.3 讨论
来自 C Python 的程序员常使用 for 循环。它们在 R 中较少见,但偶尔也有用。
为了说明,这个 for 循环打印前五个整数及其平方。它将 x 依次设置为 1234
5,每次执行循环中的操作:
for (x in 1:5) {
cat(x, x^2, "\n")
}
#> 1 1
#> 2 4
#> 3 9
#> 4 16
#> 5 25
我们还可以迭代向量或列表的
下标
,这对于更新数据非常有用。在这里,我们用向量
1:5 初始化 v,然后通过对每个元素求平方来更新它的元素:
v <- 1:5
for (i in 1:5) {
v[[i]] <- v[[i]] ^ 2
}
print(v)
#> [1] 1 4 9 16 25
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

机器学习实战:基于Scikit-Learn、Keras 和TensorFlow (原书第2 版)

机器学习实战:基于Scikit-Learn、Keras 和TensorFlow (原书第2 版)

Aurélien Géron
大规模数据分析和建模:基于 Spark 与 R

大规模数据分析和建模:基于 Spark 与 R

Javier Luraschi, Kevin Kuo, Edgar Ruiz
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey

Publisher Resources

ISBN: 9787111656814