SymbolixAU SymbolixAU - 10 months ago 100
R Question

Checking for a list using Rcpp fails

Consider these examples using

Rcpp
to check various data types. Why does my check for
is_list
return
FALSE
?

library(Rcpp)

cppFunction('bool is_list(SEXP data) {
return Rf_isList(data) ? true : false;
}')

cppFunction('bool is_data_frame(SEXP x) {
return Rf_inherits(x, "data.frame") ? true : false;
}')

cppFunction('bool is_integer(SEXP data) {
return Rf_isInteger(data) ? true : false;
}')

is_data_frame(list(a = 1))
# [1] FALSE
is_data_frame(data.frame())
# [1] TRUE
is_integer(1)
# [1] FALSE
is_integer(1L)
# [1] TRUE

## However, this is unexpected
is_list(list(a = 1))
[1] FALSE


References




Answer Source

Use Rf_isNewList instead. (Apparently the representation of lists changed at some point.)

This works:

library(Rcpp)

cppFunction('bool is_list(SEXP data) {
    return Rf_isNewList(data) ? true : false;
}')

is_list(list(a = 1))
#> TRUE

is_list(1)
#> FALSE

I think it's more idiomatic to do the following instead:

cppFunction('bool is_list(SEXP data) {
    return (TYPEOF(data) == VECSXP);
}')

This has the side-benefit that NULL is not a list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download