'How to return the result in a recursive permutation function in R? [duplicate]
folk, I am quite new to coding and R. I am practicing writing a permutation function in R, and this this function was supposed to return all possibilities of rearrangement elements in a given vector. Here is my code:
"
result<-data.frame()
counts<-0
swap<-function(arrx,a,b){p1=arrx[a];p2=arrx[b];arrx[a]=p2;arrx[b]=p1;return(arrx)}
permu<-function(arrx,k){
m=length(arrx)
if (k==m)
{cat(arrx,"\n");counts=counts+1;result<-rbind(result,arrx)}
else {for (i in k:m){
arrx<- swap(arrx,i,k)
permu(arrx,k+1)
arrx<- swap(arrx,i,k)
}}
return(list(result,counts))}
permu(c("a","b","c"),1)
" after running it in R studio, I got this: "
> permu(c("a","b","c"),1)
a b c
a c b
b a c
b c a
c b a
c a b
[[1]]
data frame with 0 columns and 0 rows
[[2]]
[1] 0
" it seems that it can do the recursive permute job correctly. However, it cannot save the result in a dataframe via "return()". I googled a bit and found that in python there is a function called "yield", but in R, I cannot figure this out. How should I save the results in the way I want in R?
Solution 1:[1]
You assigned the value of resultwhich was an empty data.frame to the first item in a list and the value of counts which was a length one numeric vector with value 0 (both obtained from the global environment. You did nothing with the arrx object so it was garbage collected. It also looks like you might have intended to have the rbind operation and the "incremetation" of counts to occur inside the loop. At the moment there doesn't appear to be any storage of "results" in result.
R is not great at recursion. If you want to learn how it is supported you can look at the ?Recall help page.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IRTFM |
