【发布时间】:2022-07-22 00:35:45
【问题描述】:
我有一个当前正在工作的函数,但我认为可能有更好的方法让它工作,而无需事先对数据进行如此多的操作。基本上,如果我的列中的值大于它之前和之后的两个值,我将返回一个简单的 TRUE 或 FALSE。
y1 #a single vector column of values
for (i in 3:length(y1)){ #for every number starting at 3 (because for 2 and 1 you can't go back two)
if(y1[i] > y1[i-1] && y1[i] > y1[i-2] && y1[i] > y1[i+1] && y1[i] > y1[i+2]){ #if the number is greater than 2 before and 2 after...
y2[i] <- 'TRUE' #if it is true, write true. Here y2[i] you're saving the results in the blank vector
} else {
y2[i] <- 'FALSE' } #opposite here
print(y2[i])
这工作正常,但正如你所见,我必须在我的 for 循环中从 3 开始,否则我会收到错误,因为第一个和第二个值以及最后两个值无法计算 [i -1]、[i-2] 或 [i+1] 和 [i+2]。如果我为 i:length(y1) 这样做,它将不起作用,我还必须在数据集上添加两个零,以免出错/能够“计算”最后一个 TRUE/FALSE 值。
有什么方法可以清理实际的函数,这样我就不必事先操作数据了?本质上,该函数只为我的数据中的前两个和最后两个值给我一个空值吗?
【问题讨论】:
标签: r function if-statement