2017-04-12 39 views
1

我試圖從data.frame中提取和子集包含日期信息的向量。我能夠成功地從DataFrame中提取出DateVector;但是,嘗試子集數據時收到錯誤。Subsetting DateVector

下面的工作正常,/* */圍繞DateVector子集。

Rcpp::cppFunction(' 
Rcpp::DataFrame test(DataFrame x, StringVector y) { 

    StringVector New = x["string_1"]; 
    std::string KEY = Rcpp::as<std::string>(y[0]); 
    Rcpp::LogicalVector ind(New.size()); 

    for(int i = 0; i < New.size(); i++){ 
    ind[i] = (New[i] == KEY); 
    } 


    Rcpp::StringVector st1 = x["string_1"]; 
    Rcpp::StringVector Id = x["ID"]; 
    Rcpp::StringVector NameId = x["NameID"]; 
    Rcpp::DateVector StDate = x["StartDate"]; 
    Rcpp::DateVector EtDate = x["EndDate"]; 

    /* 
    Rcpp::DateVector StDate_sub = StDate[ind]; 
    Rcpp::DateVector EtDate_sub = EtDate[ind]; 
    */ 

    return Rcpp::DataFrame::create(Rcpp::Named("string_1") = st1[ind], 
           Rcpp::Named("ID") = Id[ind], 
           Rcpp::Named("NameID") = NameId[ind]/*, 
           Rcpp::Named("StartDate") = StDate_sub, 
           Rcpp::Named("EndDate") = EtDate_sub*/ 
           ); 
}') 

有兩個顯着的錯誤,我得到:

error: invalid user-defined conversion from 'Rcpp::LogicalVector {aka Rcpp::Vector<10, Rcpp::PreserveStorage>}' to 'int' [-fpermissive]

Rcpp::DateVector StDate_sub = StDate[ind]

二是:

no known conversion from 'SEXP' to 'int' file585c1863151c.cpp:23:53: error: conversion from 'Rcpp::Date' to non-scalar type 'Rcpp::DateVector {aka Rcpp::oldDateVector}' requested

Rcpp::DateVector EtDate_sub = EtDate[ind];

我看了看文檔,但無法找到一個方法。對不起,如果我錯過了。我在data.frame中有幾個日期變量。我正在使用Rcpp將嵌套for循環中的數據集子集。目前,它花費了太多時間。由於某些處理需要子集數據集,因此我無法在data.tabledplyr中實現它。

+1

看起來子集運算符的實現在新的和舊的'DateVector'實現下都存在問題:/ – coatless

回答

2

首先,由於沒有定義的數據集,因此您的示例不具有最低程度的可重複性。

其次,您正在制定(英雄?)假設,即通過索引向量爲日期向量定義分配。出現它可能不是。

第三,循環只是微不足道的。修改後的代碼如下。建設順利,不知道它是否運行,因爲您沒有提供參考數據

#define RCPP_NEW_DATE_DATETIME_VECTORS 1 
#include <Rcpp.h> 

using namespace Rcpp; 

// [[Rcpp::export]] 
Rcpp::DataFrame dftest(DataFrame x, StringVector y) { 

    StringVector New = x["string_1"]; 
    std::string KEY = Rcpp::as<std::string>(y[0]); 
    Rcpp::LogicalVector ind(New.size()); 

    for(int i = 0; i < New.size(); i++){ 
    ind[i] = (New[i] == KEY); 
    } 


    Rcpp::StringVector st1 = x["string_1"]; 
    Rcpp::StringVector Id = x["ID"]; 
    Rcpp::StringVector NameId = x["NameID"]; 
    Rcpp::DateVector StDate = x["StartDate"]; 
    Rcpp::DateVector EtDate = x["EndDate"]; 

    int n = sum(ind); 
    Rcpp::DateVector StDate_sub = StDate(n); 
    Rcpp::DateVector EtDate_sub = EtDate(n); 
    for (int i=0; i<n; i++) { 
    StDate_sub[i] = StDate(ind[i]); 
    EtDate_sub[i] = EtDate(ind[i]); 
    } 

    return Rcpp::DataFrame::create(Rcpp::Named("string_1") = st1[ind], 
           Rcpp::Named("ID") = Id[ind], 
           Rcpp::Named("NameID") = NameId[ind], 
           Rcpp::Named("StartDate") = StDate_sub, 
           Rcpp::Named("EndDate") = EtDate_sub); 
} 
相關問題