当我使用 Rcpp 向数据帧添加一列时,它在返回后不再呈现为数据帧。我试图尽可能接近添加列的原始示例,但无论我如何对其进行变异,我都会得到一个列表。
正如您在下面看到的,当我通过分配给新键或使用push_back().
此处可运行的reprex ,或下面复制的输出
fun <- Rcpp::cppFunction('
List DataFrameExample() {
Rcpp::IntegerVector a = {1, 2, 3};
// create a new data frame
Rcpp::DataFrame DF = Rcpp::DataFrame::create(
Rcpp::Named("a1")=a
);
Rcpp::DataFrame NDF = clone(DF);
//NDF.push_back(a, "a2");
NDF["a2"] = a;
return(Rcpp::List::create(
Rcpp::Named("origDataFrame")=DF,
Rcpp::Named("newDataFrame")=NDF)
);
}')
dfs <- fun()
dfs
Run Code Online (Sandbox Code Playgroud)
## $origDataFrame
## a1
## 1 1
## 2 2
## 3 3
##
## $newDataFrame
## $newDataFrame$a1
## [1] 1 2 3
##
## $newDataFrame$a2
## [1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
## $origDataFrame
## a1
## 1 1
## 2 2
## 3 3
##
## $newDataFrame
## $newDataFrame$a1
## [1] 1 2 3
##
## $newDataFrame$a2
## [1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
## $origDataFrame
## [1] "data.frame"
##
## $newDataFrame
## [1] "list"
Run Code Online (Sandbox Code Playgroud)
lapply(dfs, class)
Run Code Online (Sandbox Code Playgroud)
## $origDataFrame
## $origDataFrame$names
## [1] "a1"
##
## $origDataFrame$class
## [1] "data.frame"
##
## $origDataFrame$row.names
## [1] 1 2 3
##
##
## $newDataFrame
## $newDataFrame$names
## [1] "a1" "a2"
Run Code Online (Sandbox Code Playgroud)
(Rcpp 1.0.3 在 Catalina 10.15.1 上为 R 3.6.0)
不幸的是,当添加新列时,Rcpp::DataFrame对象会丢失其class属性,将其扔回Rcpp::List. 可以在 C++ 中通过Rcpp::Rcout << NDF.hasAttribute("class") << std::endl;在添加新列之前和之后添加来验证这一点。幸运的是,很容易将Rcpp::ListaRcpp::DataFrame显式转换为 a :
fun <- Rcpp::cppFunction('
List DataFrameExample() {
Rcpp::IntegerVector a = {1, 2, 3};
// create a new data frame
Rcpp::DataFrame DF = Rcpp::DataFrame::create(
Rcpp::Named("a1")=a
);
Rcpp::DataFrame NDF = clone(DF);
Rcpp::Rcout << NDF.hasAttribute("class") << std::endl;
//NDF.push_back(a, "a2");
NDF["a2"] = a;
Rcpp::Rcout << NDF.hasAttribute("class") << std::endl;
return(Rcpp::List::create(
Rcpp::Named("origDataFrame") = DF,
Rcpp::Named("newDataFrame") = Rcpp::DataFrame(NDF))
);
}')
dfs <- fun()
#> 1
#> 0
dfs
#> $origDataFrame
#> a1
#> 1 1
#> 2 2
#> 3 3
#>
#> $newDataFrame
#> a1 a2
#> 1 1 1
#> 2 2 2
#> 3 3 3
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v0.3.0)于 2019 年 12 月 17 日创建
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |