【问题标题】:How do I write a loop which sums up my precipitation values如何编写一个总结我的降水值的循环
【发布时间】:2020-06-06 11:43:26
【问题描述】:

我正在寻找一个遍历降水值向量并将该值添加到前一个值的循环 例如:

precipitation <- c(0, 2, 0, 0.1, 0.5, 0.6, 0, 1)

我很想得到一个向量,它将像这样的值加起来

precipitationSum <- c(0, 2, 0, 0.1, 0.5, 0.6, 0, 1)
print(precipitationSum)

希望描述有意义!

任何帮助都会很棒!

【问题讨论】:

  • 在 R 中尽可能避免循环。有许多函数可以直接应用于向量,例如 sum()mean()。您还可以在不循环单个元素的情况下对整个向量执行乘法或加法等操作precipitation + 1 将返回一个向量,其中每个元素都增加 1。

标签: r loops


【解决方案1】:

你可以使用cumsum函数来计算一个向量的累积和:

precipitationSum <- cumsum(precipitation)

这将为您提供以下结果:

[1] 0.0 2.0 2.0 2.1 2.6 3.2 3.2 4.2

【讨论】:

  • 谢谢!不知道这个功能!它工作:)
【解决方案2】:
precipitation <- c(0, 2, 0, 0.1, 0.5, 0.6, 0, 1)
precipitation = unlist(precipitation)
print("This loop calculates the partial sums of precipitation")
myList <- unlist(list(1:length(precipitation)))
print(myList)
for(i in 1:length(precipitation)) {
  if(i == 1) {
      myList[i] <- precipitation[i]
  }
  else {
      myList[i] <- myList[i-1] + precipitation[i]
  }
}

print(myList)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多