向量化(非循环)解决方案返回错误的结果(for-loop解决方案返回正确的结果) [英] Vectorized (non-loop) solution returns wrong result (solution with for-loop returns correct result)

查看:136
本文介绍了向量化(非循环)解决方案返回错误的结果(for-loop解决方案返回正确的结果)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有理论上相同的解决方案,一个是向量化解决方案,另一个是for循环。但矢量化的解决方案返回错误的结果,我想明白为什么。解决方案的逻辑很简单:需要用矢量中以前的非NA值替换NA。

$ $ p $ $ $ $ c $#$ vector
f1 (is.na(x))
x [idx]< -x [ifelse(idx> 1,idx-1,1) ](b)(b)(b)(b)(b)(b)(b)(b)如果(is.na(x [i])&&!is.na(x [i-1])){
x [i] < - x [i-1] (NA,NA,1,2,3,NA,NA,6,7),其中,
f1(v)
#[1] NA NA 1 2 3 3 NA 6 7
f2(v)
#[1] NA NA 1 2 3 3 3 6 7


解决方案

这两段代码是不同的。 >


  • 第一个将 NA 替换为前一个元素,如果这个不是NA。 li>
  • 第二个用前一个元素替换 NA ,如果这个元素不是 NA ,但以前的eleme nt可以是之前 NA 替换的结果。


哪一个是正确取决于你。第二种行为更难于矢量化,但也有一些已经实现的功能,比如 zoo :: na.locf

<或者,如果您只想使用基本软件包,则可以查看此答案


I have theoretically identical solutions, one is vectorized solution and another is with for-loop. But vectorized solution returns wrong result and I want to understand why. Solution's logic is simple: need to replace NA with previous non-NA value in the vector.

# vectorized
f1 <- function(x) {
    idx <- which(is.na(x))
    x[idx] <- x[ifelse(idx > 1, idx - 1, 1)]
    x
}

# non-vectorized
f2 <- function(x) {
    for (i in 2:length(x)) {
        if (is.na(x[i]) && !is.na(x[i - 1])) {
            x[i] <- x[i - 1]
        }
    }
    x
}

v <- c(NA,NA,1,2,3,NA,NA,6,7)
f1(v)
# [1] NA NA  1  2  3  3 NA  6  7
f2(v)
# [1] NA NA  1  2  3  3  3  6  7

解决方案

The two pieces of code are different.

  • The first one replace NA with the previous element if this one is not NA.
  • The second one replace NA with the previous element if this one is not NA, but the previous element can be the result of a previous NA substitution.

Which one is correct really depends on you. The second behaviour is more difficult to vectorize, but there are some already implemented functions like zoo::na.locf.

Or, if you only want to use base packages, you could have a look at this answer.

这篇关于向量化(非循环)解决方案返回错误的结果(for-loop解决方案返回正确的结果)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆