Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

Extracting element in a nested list in Rcpp

$
0
0

I am trying to extract an element from a list and do something with it's value using Rcpp. But I cannot make the assignment.

Here is basically what I want to achieve given in R code:

mylist = list(steps = list(`1` = list(a = 7, b = "abc"), 
                           `2` = list(a = 3), 
                           `3` = list(a = 5, b = NULL)))
# This is the desired behavior that I can program in R
step_name = "1"
b = ifelse(is.null(mylist$steps[[step_name]][["b"]]), 
           "", mylist$steps[[step_name]][["b"]])
# Do something with the value of b

The following code cannot make the assignment to b. The value of a is extracted as it should. I don't know what I'm missing here.

library(Rcpp)
cppFunction('int foo(Rcpp::List x, std::string step_name) {
  Rcpp::List steps = x("steps");
  Rcpp::List step = steps(step_name);
  int a = step("a");
  //// Not declaring b causes "not declared in this scope" error 
  //// so I initialize it with a random value.
  std::string b = "random";
  if (step.containsElementNamed("b")){
    Rcout << "b is in List!"<< "\\n";
    if (!Rf_isNull(step("b"))) {
      Rcout << "b is not NULL!"<< "\\n";
      if (TYPEOF(step("b")) == STRSXP)
        Rcout << "b is character!"<< "\\n";
      std::string b = step("b");
    } else {
      Rcout << "b is NULL!"<< "\\n";
      std::string b = "efg";
    }          
  } else {
    Rcout << "b is not in List!"<< "\\n";
    std::string b = "xyz";
  }
  Rcout << "The Value of b is "<< b << ".\\n";
  if (b == "abc") {
    //// Do something with the value of b
  }       
  return a;
}')

foo(mylist, "1")
## b is in List!
## b is not NULL!
## b is character!
## The Value of b is random.
## [1] 7
foo(mylist, "2")
## b is not in List!
## The Value of b is random.
## [1] 3
foo(mylist, "3")
## b is in List!
## b is NULL!
## The Value of b is random.
## [1] 5

Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>