将R代码转换为Rcpp——for循环、向量输入、向量输出

Convert R code to Rcpp - for loop, vector input, vector output

我是 Rcpp 和 C++ 的初学者。如果我能看到一个与我的上下文相关的工作示例,它可能会对我的旅程有所帮助。

让我们使用以下 R 代码:

value <-c(0.2,0.3,0.4,0.5,0.6,-2.0,0.7,0.4,-10,0.1,0.2,0.4,3.0,0.6,0.7,0.8,-1.2,0.6,0.7,0.8,0.3,0.5,2,0.1,0.2)
res <- NULL
while (length(res) < length(value)) {
  if (value[length(res)+1] < -1) {
    res <- c(res, rep(1,5))
  } else {
    res <- c(res, 0)
  }
}

数字输出:

> str(res)
 num [1:25] 0 0 0 0 0 1 1 1 1 1 ...

代码是一个 for 循环,找到 < -1 的实例,然后附加一个带有 rep 1.5 次的向量 else if not -1 do 0.

接下来我想将它发送给 Rcpp:

我在这里遵循一些例子:

Hadley Wickham and http://dirk.eddelbuettel.com

我的转换尝试如下:

cppFunction('double resC(NumericVector x) {
  int n = x.size();
            double res = 0;
            for(int i = ; i < n; ++i) {
  if (value[i] < -1) { 
  res += c(res, rep(1,5));
  } else {
    res += c(res, 0);
  }         
            return res;
            }')


resC(value)

C++ 可以像 R 一样附加到向量吗?它看起来不像是直接的相似交换。

我选择用 Julia 编写代码

逻辑相同只是将大括号放在:

signal = [0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 ]

n_day = zeros(signal)
i = 1
j = 1
for i in 1:length(signal)
if signal[i] == 1
    n_day[i] = 1
    j = 1
    print("i =", i)
while(j<=4)
  # Carry over index position
        n = i + j  # carry over index position
    n_day[n] = 1
    j = j + 1
end
j=1
n=1
end
end

输出:

julia> print(n_day)
[0 1 1 1 1 1 1 0 1 1 1 1 1 0 0 0 1 1 1 1 1 0]