将R代码转换为Rcpp-for循环、向量输入、向量输出 我是Rcpp和C++的初学者。如果我能看到一个与我的环境相关的工作示例,它可能会对我的旅程有所帮助

将R代码转换为Rcpp-for循环、向量输入、向量输出 我是Rcpp和C++的初学者。如果我能看到一个与我的环境相关的工作示例,它可能会对我的旅程有所帮助,r,rcpp,R,Rcpp,让我们使用以下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))

让我们使用以下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)
  }
}
代码是一个for循环,查找
<-1
的实例,然后用rep 1添加一个向量,如果不是-1,则添加5次,否则为0

接下来,我想将此发送给Rcpp:

以下是一些例子:

我的转换尝试如下:

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)
cppFunction('double resC(数值向量x)){
int n=x.size();
双res=0;
for(int i=;i

< > C++可以以同样的方式附加到向量中吗?它看起来不像是一个类似的相似的交换。< /P> < P>我选择在朱丽亚

中编码它。 逻辑相同,只需将花括号插入:

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

你不应该在循环中增长向量。你不应该在R中做它,绝对不能在C++中。
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]