我有一个数据框,其中的列没有名字,我想在RCPP中给它们命名,我该怎么做?

问题描述 投票:0回答:1

我对Rcpp很陌生。我有一个数据框,它的列没有名字,我想用Rcpp来命名它们。我如何才能做到这一点?也就是说,这个数据框是一个输入,然后我想在第一步中命名它的列,请告诉我如何做。

rcpp
1个回答
1
投票

欢迎来到StackOverflow。 我们可以修改现有的例子,在 RcppExamples 包 (你可能会发现这对你很有帮助,就像 Rcpp 文档的其他部分一样)来显示这一点。

实质上,我们只是将一个 names 属性。

编码

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List DataFrameExample(const DataFrame & DF) {

    // access each column by name
    IntegerVector a = DF["a"];
    CharacterVector b = DF["b"];
    DateVector c = DF["c"];

    // do something
    a[2] = 42;
    b[1] = "foo";
    c[0] = c[0] + 7; // move up a week

    // create a new data frame
    DataFrame NDF = DataFrame::create(Named("a")=a,
                                      Named("b")=b,
                                      Named("c")=c);

    // and reassign names
    NDF.attr("names") = CharacterVector::create("tic", "tac", "toe");

    // and return old and new in list
    return List::create(Named("origDataFrame") = DF,
                        Named("newDataFrame") = NDF);
}

/*** R
D <- data.frame(a=1:3,
                b=LETTERS[1:3],
                c=as.Date("2011-01-01")+0:2)
rl <- DataFrameExample(D)
print(rl)
*/

演示

R> Rcpp::sourceCpp("~/git/stackoverflow/61616170/answer.cpp")

R> D <- data.frame(a=1:3,
+                 b=LETTERS[1:3],
+                 c=as.Date("2011-01-01")+0:2)

R> rl <- DataFrameExample(D)

R> print(rl)
$origDataFrame
   a   b          c
1  1   A 2011-01-08
2  2 foo 2011-01-02
3 42   C 2011-01-03

$newDataFrame
  tic tac        toe
1   1   A 2011-01-08
2   2 foo 2011-01-02
3  42   C 2011-01-03

R> 

如果你把这一行注释出来,就会得到旧的名字。

© www.soinside.com 2019 - 2024. All rights reserved.