繁体   English   中英

R到C ++代码以遍历数据帧列表(Rcpp)

[英]R to C++ code to loop through list of data frames (Rcpp)

我有一个数据帧列表,我想遍历列表中每个数据帧的列,以使用c ++代码创建新变量(因为我正在学习Rcpp)。

输入如下所示:

 $`df1`
 a  b  c
 5 30  2
 4  2 15
 3  2 17

$df2
a  b  c
5 30  2
4  2 15
3  2 17 

理想情况下,输出为:

    $`df1`
    a     b     c
    5.02 30.02  2
    4.15 2.15   15
    3.17 2.17   17

    $df2
    a     b      c
    5.02  30.02  2
    4.15  2.15   15
    3.17  2.17   17

我想在之后删除c列,但现在我正试图找出执行此操作的c ++代码。

注意:我希望C列第2行的2粘贴时为02,而不是20(因此它们的宽度相同且准确)。

我不确定您要确切执行的操作,但是这里有一些快速而肮脏的代码可以遍历数据帧列表中的列:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List listDf(Rcpp::List l) {
  for (int i = 0; i < l.length(); ++i) {
    Rcpp::DataFrame df = Rcpp::as<Rcpp::DataFrame>(l[i]);
    for (int j = 0; j < df.cols(); ++j) {
      Rcpp::NumericVector col = df[j];
      df[j] = 1.23 * col;
    }
  }
  return l;
}

/*** R
set.seed(42)
df1 <- data.frame(a = sample(1:100, 3),
                  b = sample(1:100, 3),
                  c = sample(1:100, 3))

df2 <- data.frame(a = sample(1:100, 3),
                  b = sample(1:100, 3),
                  c = sample(1:100, 3))

l <- list(df1 = df1, df2 = df2)

listDf(l)

*/

而且,如果您实际上想将最后一列的1/100添加到其他列,则可以使用:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List listDf(Rcpp::List l) {
  for (int i = 0; i < l.length(); ++i) {
    Rcpp::DataFrame df = Rcpp::as<Rcpp::DataFrame>(l[i]);
    Rcpp::NumericVector last = df[df.cols() - 1];
    for (int j = 0; j < df.cols() - 1; ++j) {
      Rcpp::NumericVector col = df[j];
      df[j] = col + last / 100.0;
    }
  }
  return l;
}

/*** R
set.seed(42)
df1 <- data.frame(a = sample(1:100, 3),
                  b = sample(1:100, 3),
                  c = sample(0:99, 3))

df2 <- data.frame(a = sample(1:100, 3),
                  b = sample(1:100, 3),
                  c = sample(0:99, 3))

l <- list(df1 = df1, df2 = df2)

listDf(l)

*/

输出:

> listDf(l)
$df1
      a     b  c
1 92.73 84.73 73
2 93.13 64.13 13
3 29.64 51.64 64

$df2
       a     b  c
1  71.94 94.94 94
2  46.96 26.96 96
3 100.11 46.11 11

@Ralf Stubner认为我会给你视觉效果

df1 <- data.frame(a = sample(1:100, 3), b = sample(1:100, 3), c = sample(0:99, 3))

给出(没有set.seed):

  df1
  a  b  c
  28 70 70
  14 63  5
   8 12 20

dsets<-do.call("list", replicate(10, df1, simplify=FALSE)) #to replicate this 10 times 
#and store as list 

运行这个

       listDf(dsets)

并输出如下:

[[9]]
  a    b  c
35.0 77.0 70
14.5 63.5  5
10.0 14.0 20

[[10]]
  a    b  c
35.0 77.0 70
14.5 63.5  5
10.0 14.0 20

我可能缺少一些简单的东西?

暂无
暂无

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

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