我有一个数据框,其中的列没有名称,我想在 RCPP 中命名它们?我该怎么做?
I have a data frame in which its columns do not have name and I want to name them in RCPP?How can I do that?
我是 Rcpp 的新手。我有一个数据框,其中的列没有名称,我想在 Rcpp 中命名它们。我怎样才能做到这一点?也就是说,这个数据框是一个输入,然后我想在第一步中命名它的列。
请告诉我该怎么做。
欢迎使用 Whosebug。我们可以修改 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/Whosebug/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>
如果您注释掉该行,您将获得旧名称。
我是 Rcpp 的新手。我有一个数据框,其中的列没有名称,我想在 Rcpp 中命名它们。我怎样才能做到这一点?也就是说,这个数据框是一个输入,然后我想在第一步中命名它的列。 请告诉我该怎么做。
欢迎使用 Whosebug。我们可以修改 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/Whosebug/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>
如果您注释掉该行,您将获得旧名称。