[Rcpp-devel] Filling a list with iterator, or setting names from CharacterVector/SEXP?
Christian Gunning
xian at unm.edu
Sat Sep 1 08:44:07 CEST 2012
On Fri, Aug 31, 2012 at 5:50 AM, Dirk Eddelbuettel <edd at debian.org> wrote:
>
> Yes -- I needed this the other day to return what I got in C++ as a
> std::vector<std::string> vecstr. I used something like
>
> Rcpp::CharacterVector charvec( vecstr.begin(), vecstr.end() )
Ok, I was wondering about std::vector. But how do I go the other way
and get a std::vector<std::string> vecstr from a CharacterVector?
Can I use as<std::string>() and then iterate over the CharacterVector?
>
> but I later realized that Rcpp::wrap() already covered this case so it
> reduced to
>
> return vecstr;
>
> instead :)
>
> You should be able to to do better than your loop below as you already have a
> vector in 'rownames'. My not just transform that into a list directly as below?
>
> Dirk
>
>
> R> library(inline)
> R>
> R> f <- cxxfunction(signature(xs="character"), plugin="Rcpp", body='
> + Rcpp::CharacterVector xv(xs);
> + return Rcpp::List( xv );
> + ')
> R>
> R> x <- c("Moe", "Curly", "Larry")
> R> f(x)
> [[1]]
> [1] "Moe"
>
> [[2]]
> [1] "Curly"
>
> [[3]]
> [1] "Larry"
My use-case is access-by-name. So in this example I want, for example:
R> f(x)
[["Moe"]]
[1] 1
[["Curly"]]
[1] 2
Of course, I can just hand in list(Moe=1, Curly=2), but then I still
don't know how to get the names of the list out of the list into a
CharacterVector or std::vector<std::string>. Does this sort of make
sense?
Thanks!
-Christian
--
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
More information about the Rcpp-devel
mailing list