gpt4 book ai didi

r - 错误 : could not convert using R function : as. 数据帧

转载 作者:行者123 更新时间:2023-12-04 15:26:05 24 4
gpt4 key购买 nike

我正在尝试读取 C++ 中的文本文件并将其作为 DataFrame 返回。我已经创建了一个框架方法来读取文件并返回它:

// [[Rcpp::export]]
DataFrame rcpp_hello_world(String fileName) {

int vsize = get_number_records(fileName);
CharacterVector field1 = CharacterVector(vsize+1);

std::ifstream in(fileName);

int i = 0;
string tmp;
while (!in.eof()) {
getline(in, tmp, '\n');
field1[i] = tmp;
tmp.clear( );
i++;
}
DataFrame df(field1);
return df;
}

我在 R 中使用:

> df <- rcpp_hello_world( "my_haproxy_logfile" )

但是,R 返回以下错误:

Error: could not convert using R function : as.data.frame

我做错了什么?

非常感谢。

最佳答案

DataFrame 对象是“特殊的”。我们的首选用法是通过 return Rcpp::DateFrame::create ... 您将在许多已发布的示例中看到它,包括在此处的许多答案中。

这是一个from a Rcpp Gallery post :

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
DataFrame modifyDataFrame(DataFrame df) {

// access the columns
Rcpp::IntegerVector a = df["a"];
Rcpp::CharacterVector b = df["b"];

// make some changes
a[2] = 42;
b[1] = "foo";

// return a new data frame
return DataFrame::create(_["a"]= a, _["b"]= b);
}

虽然着重于修改 DataFrame,但它会顺便向您展示如何创建 DataFrame。 _["a"] 快捷方式也可以写成我更喜欢的 Named("a")

关于r - 错误 : could not convert using R function : as. 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com