[Rcpp-devel] Doubt about best pratices
Jeff Newmiller
jdnewmil at dcn.davis.ca.us
Sun May 1 07:36:03 CEST 2022
It is not possible to convert a data frame to a matrix without copying data.
But normally algorithms that need a matrix become noticeably less efficient when applied to data frames. If this is your case, I would simply encourage the user to pass a matrix into your function in the first place. The sooner the right data structure is used, the less gratuitous conversion needs to happen.
I think there is no one answer to this though... what is your algorithm? Would it work well on column vectors?
On April 30, 2022 9:38:49 PM PDT, Roberto Spadim <roberto at spadim.com.br> wrote:
>Uhm
>Converting from one to other copy data? From dataframe to matrix at least?
>
>Em sáb., 30 de abr. de 2022 às 14:26, Jeff Newmiller <
>jdnewmil at dcn.davis.ca.us> escreveu:
>
>> A data frame is designed to represent different types in different
>> columns. A matrix is designed so that all elements are the same.
>>
>> It sounds like you need matrices for your algorithm. I would simply
>> require that... or attempt to convert it immediately and stop if the result
>> is not numeric.
>>
>> On April 30, 2022 10:16:04 AM PDT, Roberto Spadim <roberto at spadim.com.br>
>> wrote:
>> >Hi folks!
>> >
>> >What's the best pratices to accept a dataframe and numericmatrix in a
>> function?
>> >
>> >Should I have two different methods to deal with NumericMatrix and
>> DataFrame?
>> >Could I convert DataFrame to matrix? What's the impact of doing this,
>> >i.e. does the as.matrix copy dataframe data?
>> >
>> >Thanks in advance!
>> >
>> >---
>> >Today I'm doing something like this:
>> >
>> >void RCPP_function(const RObject &vec, const RObject &mat) {
>> > if(mat.isNULL())
>> > Rcpp::stop("mat can't be null");
>> > NumericMatrix variable_matrix;
>> > if (is<NumericMatrix>(mat))
>> > variable_matrix = as<NumericMatrix>(mat);
>> > else
>> > variable_matrix = Rcpp::internal::convert_using_rfunction(mat,
>> "as.matrix");
>> >
>> > NumericVector variable_vector;
>> > if((is<NumericVector>(target) || is<DataFrame>(target)) &&
>> !target.isNULL()){
>> > variable_vector=as<NumericVector>(target);
>> > }else{
>> > variable_vector=colMeans(variable_matrix);
>> > }
>> >
>> > ...
>> > do something with data
>> > but here it's sure to be:
>> > NumericVector (variable_vector)
>> > NumericMatrix (variable_matrix)
>> > ...
>> >}
>> >
>> >
>> >--
>> >Roberto Spadim
>> >_______________________________________________
>> >Rcpp-devel mailing list
>> >Rcpp-devel at lists.r-forge.r-project.org
>> >https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>> --
>> Sent from my phone. Please excuse my brevity.
>>
--
Sent from my phone. Please excuse my brevity.
More information about the Rcpp-devel
mailing list