I have a simple R script that takes a character vector as input and returns a matrix with a half diallel. I have a different version with expand.grid(), that is faster and works well, but was curious about rcpp and this seemed simple enough... I have ran into several issues in the c++ code with trying to concatenate the parents and save those to either a vector or matrix like I'm doing in the R example. I did get an rcpp function to print out part of the output I want (cppDiallel function), but there's clearly (many things) I'm not understanding about C++ to get this to work right (see the second c++ function cppDiallel2). Reproducible example is below.
Edit: The cppDiallel2 function compiles but returns an error I also don't understand.
ges <- c("inb1", "inb2", "inb3")
Rdiallel <- function(ges){
n <- length(ges)
out <- matrix(NA, nrow=(n*(n-1))/2, ncol=3)
colnames(out) <- c("cross", "p1", "p2")
k <- 1
for(i in 1:length(ges)){
p1 <- ges[i]
for(j in 1:length(ges)){
p2 <- ges[j]
if(i < j){
out[k, 1] <- paste(p1, p2, sep="/")
out[k, 2] <- p1
out[k, 3] <- p2
k <- k + 1
}
}#end j
}#end i
return(out)
}#end Rdiallel
Rcpp::cppFunction('CharacterVector cppDiallel(CharacterVector ges){
int n =ges.size();
CharacterVector p1(1), p2(1);
for(int i=0; i < n; i++){
p1 = ges[i];
for(int j=0; j < n; j++){
p2 = ges[j];
if(i < j){
std::cout << p1 << "/" << p2 << std::endl;
}
}// end j
}// end i
return 0;
}')
Rcpp::cppFunction('CharacterMatrix cppDiallel2(CharacterVector ges){
int n =ges.size();
CharacterVector p1(1), p2(1);
CharacterMatrix out((n*(n-1))/2,3);
for(int i=0; i < n; i++){
p1 = ges[i];
for(int j=0; j < n; j++){
p2 = ges[j];
if(i < j){
//out(i,1) = p1 + "/" + p2;
out(i,1) = p1;
out(i,2) = p1;
out(i,3) = p2;
//std::cout << p1 << "/" << p2 << std::endl;
}//end if
}// end j
}// end i
return out;
}')
#works
Rdiallel(ges)
#works
cppDiallel(ges)
#compiles but gives error
cppDiallel2(ges)