gpt4 book ai didi

r - 缺失值 true/false : error in loop not in one-off

转载 作者:行者123 更新时间:2023-11-28 20:20:59 24 4
gpt4 key购买 nike

我是 R 的新手,我在想编写代码的循环测试中遇到问题。使用如下所示的数据框 (tabetest):

    Date    25179M103
1 14977 77.7309
2 14978 77.2567
3 14979 77.7507

我有:

> if (tabetest[3,"Date"] - tabetest[1,"Date"] > 1){ print("ok") }

[1] "ok"

但是:

j = 1 
position = 1
price = tabetest

for (i in 1:nrow(tabetest) - position){
if (tabetest[i + position,"Date"] - tabetest[position,"Date"] > 20{
price[i + position,j] = price[i + position,j] / price[position,j] - 1}
position = position + 1
}

返回一个错误。 R 表示在需要 true/false 的地方有一个缺失值:

 if (tabetest[i + position, "Date"] - tabetest[position, "Date"] >

我花了很多时间来解决这个错误,但仍然不明白它从何而来。

最佳答案

首先,您有操作顺序问题。您需要在 nrow(tabetest)-position

两边加上括号

以下与c(1, 2, 3) - 1相同

> 1:3-1
[1] 0 1 2

但是,这与 c(1, 2) 相同

> 1:(3-1)
[1] 1 2

但是,在您修复该问题后,您仍然会遇到问题。第二次循环,i 为 2,position 为 2。这意味着 tabetest[i + position, "Date"]NA 因为position + i == 4,但是data.frame 只有3 行。

这主要是猜测,但也许您只想在 if 语句中的条件为 TRUE 时递增 position,如下所示:

for (i in 1:(nrow(tabetest)-position)){
if(tabetest[i+position,"Date"]-tabetest[position,"Date"]>20){
price[i+position,j]=price[i+position,j]/price[position,j]-1
position=position+1
}
}

关于r - 缺失值 true/false : error in loop not in one-off,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11074820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com