简体   繁体   English

将For循环从C ++转换为R.

[英]Converting For Loop from C++ to R

I am trying to convert this c++ code to R: 我试图将此c ++代码转换为R:

 int nrow = df.nrow(), ncol = df.ncol();
  for (int i = 0; i < nrow; i++) {
    for (int j = 0; j < ncol; j++) {
      dat[i * ncol + j] = data[j * nrow + i];
    }
  }

I wrote the following codes in R: 我在R中写了以下代码:

df = cbind(x = c(0.0,0.2,0.4,0.6,0.8,1.0), y = c(0.8,1.0,0.6,0.4,0.0,0.2)))

nRows <- nrow(df)
nCols <- ncol(df)

dat <- vector(mode="numeric", length= nRows * nCols) 

for (i in 1:nRows) {
  for (j in 1:nCols) {
      dat[i * nCols + j] <- df[j * nRows + i]
    }
}

But its not giving me the desired output. 但它没有给我想要的输出。

i want to get this: 我想得到这个:

> dat
  [1] 0.0 0.8 0.2 1.0 0.4 0.6 0.6 0.4 0.8 0.0 1.0 0.2 

but instead im getting this: 但我得到这个:

> dat
  [1] 0.0 0.0 0.8  NA 1.0  NA 0.6  NA 0.4  NA 0.0  NA 0.2  NA

Can anyone help please? 有人可以帮忙吗?

It looks like you are trying to create a vector that combines two vectors, where the values of the new vector are the values of the old vectors but alternating. 看起来您正在尝试创建一个组合两个向量的向量,其中新向量的值是旧向量的值但是交替。

> # Make the vectors
> x = c(0.0,0.2,0.4,0.6,0.8,1.0)
> y = c(0.8,1.0,0.6,0.4,0.0,0.2)
> # Get the column positions and offset them
> x_col_pos = (seq_along(x) * 2) - 1
> y_col_pos = (seq_along(y) * 2)
> # Find the order of the positions to re-arrange the new vector
> z_col_pos = order(c(x_pos, y_pos))
> z = c(x, y)[z_col_pos]
[1] 0.0 0.8 0.2 1.0 0.4 0.6 0.6 0.4 0.8 0.0 1.0 0.2

This can be easily converted into a function. 这可以很容易地转换为函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM