[Rcpp-devel] Copying a NumericVector from a list within a list
Dirk Eddelbuettel
edd at debian.org
Sun Apr 13 05:06:05 CEST 2014
On 13 April 2014 at 12:01, Dion Detterer wrote:
| In R I have a list containing another list with a named element "p" containing
| a NumericVector. In other words:
|
| > recProb[[1]]$p
| [1] 0.2855202 0.6731716 0.8497825 0.7445254 0.2382722
|
| I want to copy this into a NumericVector in Rcpp.
|
| I tried using...
|
| NumericVector nv = clone(recProb[i]["p"]);
|
| ...and various other ways with no luck. (i is a variable in a loop.)
|
| What's the best way to do this with the clearest code? Any advice would be
| greatly appreciated.
What can work as a single expression in R sometimes needs to be disentangled
at the C++ level to help the compiler find its way through all the templates.
Here is a quick demo with 'p' inside a list inside a list where one gets
accessed by position and one by name:
R> sourceCpp("/tmp/dion.cpp")
R> x <- c(0.2855202, 0.6731716, 0.8497825, 0.7445254, 0.2382722)
R> innL <- list(p=x)
R> outL <- list(List1=innL)
R> fromList(outL, "p")
[1] 0.285520 0.673172 0.849782 0.744525 0.238272
R>
The code below extracts it, and has the complete example.
Hope this helps, Dirk
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector fromList(List outer, std::string name) {
List inner = outer[0]; // 0-based offsets in C++
return inner["p"];
}
/*** R
x <- c(0.2855202, 0.6731716, 0.8497825, 0.7445254, 0.2382722)
innL <- list(p=x)
outL <- list(List1=innL)
fromList(outL, "p")
*/
--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
More information about the Rcpp-devel
mailing list