无法弄清楚如何使用if语句格式化for循环



我正在学习R课程,教授没有太大帮助。关于最新作业的一个问题让我难倒了。问题如下,以及我到目前为止的答案。

8. [15 points] Given the following code,
#
# x <- rnorm(10)
#
# Do the following.
#
# (1) create a count vector named "count" of four elements and set each to 0 using the rep function.
# (2) using a for loop to process each value in the vector x, count how many times each of the following values occur in the vector x using an if statement.
# a. "value is between -1 and 1 inclusive"
# b. "value is between -2 and 2 inclusive, but not between -1 and 1",
# c. "value is between -3 and 3 inclusive, but not between -2 and -2", or
# d. "value is greater than 3 or less than -3".
# (3) print each of the four counts in the count vector using a while loop.
#
# For example, if the vector x contains the following ten values,
#
# 1.1478911  1.6183994 -2.3790632 -0.2566993  0.8923735
# -0.7523441 -0.7559083  0.9836396  1.0994189  2.5519972
#
# Then, the output should be as below.
#
# count[1] is 5
# count[2] is 3
# count[3] is 2
# count[4] is 0
x <- rnorm(10)

我的回答:

(1)count <- c(rep(0,4))

(二)

for (count in x) {
if (x > -1 & x < 1) {
print(count[1])

}

我知道我在第一部分的代码有问题,但我们在课堂上没有讨论过这样的事情,我一直在努力寻找这样的视频。请指出我正确的方向,让我知道我犯了什么错误,非常感谢!

你第一部分是正确的。也许您可以从中删除初始c()

x <- rnorm(10)
#Part 1
count <- rep(0,4)
#Part 2
for(i in x) {
if(i >= -1 && i <= 1)
count[1] <- count[1] + 1
else  if(i >= -2 && i <= 2)
count[2] <- count[2] + 1
else if(i >= -3 & i <= 3)
count[3] <- count[3] + 1
else count[4] <- count[4] + 1
}
#Part 3
i <- 0
while (i < length(count)) {
i <- i + 1
print(sprintf('count[%d] is: %d', i, count[i]))
}

请注意,有更好/有效的方法可以做到这一点,但我认为就本练习而言,这就是您的教授想要的。

>count中的 4 个插槽中的每一个都应该跟踪x中的值是否满足列出的 4 个条件之一(a.d.)。

如果我们要大声说出来,它会是这样的:

  • 查看x中的元素 1(您可以使用x[1]执行此操作)。 这是1.1478911. 这满足条件b.,所以在"b.计数器"中添加一个 1,这是count中的第二个插槽,或count[2]
  • 现在看看x中的元素 2(这x[2])......(依此类推,直到x中的最后一个元素)。

要解决此任务,您只需写出 10 个语句,分别查看x中的 10 个元素中的每一个,并根据具体情况更新count,但这很长且难以修改。

for循环有点像为上面的大声朗读部分制作模板。 因此,与其说,"好吧,现在我们在元素3上,让我们看看交易是什么",你可以说,"好吧,现在我们在元素i上......",其中i只是一个临时变量,一个仅在for循环的生命周期内存在的占位符。i占位符会自动取用我们正在迭代的向量中元素的值。

如果是for (i in 1:3)那么i将是1,然后是2,然后是3.
如果它是for (letter in c("a", "b", "c")),那么letter将是"a",然后是"b",然后是"c"。

所以你可以看到,当你写for (count in x)时,这不符合for循环的规则。 的确,我们希望在循环中的某个时刻更新count,但您已经将其放在临时占位符应该去的位置。 您可以随意称呼该占位符,但按照惯例,在循环数字时i很常见。

下面是一个示例:以下代码将从 1 开始i,并使用新整数重复循环语句中的代码,直到i达到 10:

for (i in 1:10) {
print(paste("i is", i, "and the i'th value of x is", x[i]))
}

这应该足以让你克服你坚持的部分。

一些额外的提示:

  1. 如果你想知道一个向量中有多少东西,比如x,你可以使用length(x)(试试吧,你会看到输出是10)。 因此,与其做:for(i in 1:10),不如将 10 换成length(x)
  2. count[3] <- count[3] + 1将当前
  3. 总数添加到count的第三个元素中的任何总数上加 1。

祝你好运! 有人可能会发布整个问题的答案,但如果你想完成每件作品,我希望这对你来说是一个很好的开始。

最新更新