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

标签 r

我正在学习 R 入门类(class),教授并没有给我太多帮助。最新作业的一道题把我难住了。问题如下,以及我迄今为止的答案。

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))

(2)

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]))
}

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

关于r - 无法弄清楚如何使用 if 语句格式化 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64038267/

相关文章:

r - 如何将survfit结果转换为相等的strata data.table?

r - gtsummary 回归表的生成 header

从ggplot2中的小图例框中删除边框和颜色

r - 在 R 函数中模拟静态变量

r - 更改表面颜色(使用lattice::wireframe)

r - 如何使用mapview设置Leaflet layerId

R:将绘图存储到列表中然后编织到knitr文档中

r - geom_text_repel 的控制颜色

R Leaflet Map - addPolygon地理标签

r - 如果另一个变量中的值在 dplyr 的列表中不匹配,则删除一个变量中的值