0

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • I don't see any assignment of the result to an object name. – IRTFM Jan 21 '22 at 16:34
  • Hello IRTFM, Thank you for your answer. I have "result<-rbind(result,arrx)" at the end of branch when each recursion is solved. Would you please provide suggestions on how to modify this? – Hanzeng Li Jan 21 '22 at 16:37

1 Answers1

0

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.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • ```swap<-function(arrx,a,b){p1=arrx[a];p2=arrx[b];arrx[a]=p2;arrx[b]=p1;return(arrx)} result<-data.frame() counts<-0 permu<-function(arrx,k){ m=length(arrx) if (k==m) {cat(arrx,"\n")} else {for (i in k:m){ arrx<- swap(arrx,i,k) permu(arrx,k+1) counts=counts+1;result<-rbind(result,arrx) arrx<- swap(arrx,i,k) }} return(list(result,counts))} permu(c("a","b","c"),1)``` I change the code to this, but still get a 3-row dataframe as the returned result and counts=3. What is the essence to the problem? – Hanzeng Li Jan 21 '22 at 17:30