Suppose I have the following list of vector
List <- list(c(1:3), c(4:6), c(7:9))
To get the required result I have the following code in Rcpp
totalCpp <- {"#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List t_list(List r_list) {
List results;
for (int i = 0; i < r_list.size(); ++i) {
NumericVector vec = as<NumericVector>(r_list[i]);
int sum = 0;
for (int j = 0; j < vec.size(); ++j) {
sum += vec[j];
}
results.push_back(sum); // Add the sum to the results list
}
return results;
}
"}
sourceCpp(code = totalCpp)
which returns the following
> t_list(List)
[[1]]
[1] 6
[[2]]
[1] 15
[[3]]
[1] 24
Is it possible to write this Rcpp code without using two for loops or is there any elegant way to write this code in the Rcpp?


colSums(list2DF(List)). In case, you are running an XY problen.