gpt4 book ai didi

在 NumericVector Rcpp 意外行为中返回 NA 值

转载 作者:行者123 更新时间:2023-12-02 04:21:49 25 4
gpt4 key购买 nike

我正在编写一个 cpp 函数来用下一个非 na 值替换任何 NA 值。关于替换,代码可以正常工作,但是我想为那些没有后来的非 NA 值的值返回 NA 值。

例如:

fill_backward(c(1, NA, 2)) --> 1, 2, 2

fill_backward(c(1, NA, 2, NA)) --> 1, 2, 2, NA

#include <Rcpp.h>
using namespace Rcpp;
//' given NA values fill them with the next non-na value
//' @param x A numeric vector of values
//' @details
//' Works very well in context of dplyr to carry out last-observation-carried-foward
//' for different individuals. It will NOT replace leading NA's
//' @examples /dontrun {
//' fill_forward(c(1.0, NA, 2))
//' fill_forward(c(NA, 1, NA, 2))
//' library(dplyr)
//' df <- data_frame(id = c(1, 1, 2, 2), obs = c(1.2, 4.8, 2.5, NA))
//' df %>% group_by(id) %>% mutate(obs_locf = fill_forward(obs))
//' }
//' @export
// [[Rcpp::export]]
NumericVector fill_backward(NumericVector x) {
int n = x.size();
NumericVector out = no_init(n);
for (int i = 0; i < n; ++i) {
if (R_IsNA(x[i])) {
for (int j = i+1; j < n; ++j) {
if(R_IsNA(x[j])) {
continue;
} else {
out[i] = x[j];
break;
}
//if never gets to another actual value
out[i] = NumericVector::get_na();
}
} else { //not NA
out[i] = x[i];
}
}
return out;
}

目前 fill_backward(c(NA, 1.0, NA, 2, NA, NA)) 返回:


[1] 1.000000e+00 1.000000e+00 2.000000e+00
[4] 2.000000e+00 2.156480e-314 -1.060998e-314

代替 1 1 2 2 NA NA

要返回 NA 值,它是 out[i] = NumericVector::get_na();

我也尝试过 out[i] = REAL_NA 和 out[i] = x[i]`,但似乎没有任何效果。

最后我用了同类型的实现一个fill_forward的实现,可以看here领先的 NA 应该返回为 NA - 并且它正确返回 NA 值所以我完全不知所措。

编辑:感谢@Roland 的建议修复

最佳答案

您可以使用NA 值初始化out:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector fill_backward(NumericVector x) {
int n = x.size();
NumericVector out = NumericVector(n, NumericVector::get_na());
for (int i = 0; i < n; ++i) {
if (R_IsNA(x[i])) {
for (int j = i+1; j < n; ++j) {
if(R_IsNA(x[j])) {
continue;
} else {
out[i] = x[j];
break;
}
}
} else { //not NA
out[i] = x[i];
}
}
return out;
}

测试它:

fill_backward(c(NA, 1.0, NA, 2, NA, NA))
[1] 1 1 2 2 NA NA

我应该提一下,由于您使用了 continue,您的行 out[i] = NumericVector::get_na(); 从未达到。

关于在 NumericVector Rcpp 意外行为中返回 NA 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879662/

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