Re: [R] R help on loops
Dear R users, I am stuck here: My first function returns a vector of 5 values. In my second function, I want to repeat this, a number of times, say 10 so that I have 10 rows and five columns but I keep on getting errors. See the code and results below: optm -function(perm, verbose = FALSE) { trace-c() for (k in 1:perm){ trace[k]-Rspatswap(rhox=0.6,rhoy=0.6,sigmasqG=0.081,SsqR=1)[1] perm[k]-k mat-cbind(trace, perm = seq(perm)) } if (verbose){ cat(***starting matrix\n) print(mat) } # iterate till done while(nrow(mat) 1){ high - diff(mat[, 'trace']) 0 if (!any(high)) break # done # find which one to delete delete - which.max(high) + 1L mat - mat[-delete, ] newmat-apply(mat,2,mean)[1] sdm-sd(mat[,1]) sem-sdm/sqrt(nrow(mat)) maxv-mat[1,1] minv-mat[nrow(mat),1] } stats-cbind(average=newmat,sd=sdm,se=sem,min=minv,max=maxv) stats } test-optm(perm=20) test average sd se min max trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241 itn-function(it){ siml-matrix(NA,ncol=5,nrow=length(it)) for(g in 1:it){ siml[g]-optm(perm=20) } siml-cbind(siml=siml) siml } ans-itn(5) Warning messages: 1: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 2: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 3: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 4: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 5: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length ans [,1] [,2] [,3] [,4] [,5] [1,] 0.8874234 0.8861666 0.8880521 0.8870958 0.8876469 On 5/31/2013 9:53 PM, jim holtman wrote: Is this what you want? I was not clear on your algorithm, but is looks like you wanted descending values: testx - + function(n, verbose = FALSE) + { + mat - cbind(optA = sample(n, n, TRUE), perm = seq(n)) + if (verbose){ + cat(***starting matrix\n) + print(mat) + } + # iterate till done + while(nrow(mat) 1){ + high - diff(mat[, 'optA']) 0 + if (!any(high)) break # done + # find which one to delete + delete - which.max(high) + 1L + mat - mat[-delete, ] + } + mat + } testx(20, verbose = TRUE) ***starting matrix optA perm [1,] 131 [2,] 122 [3,]73 [4,] 104 [5,] 115 [6,]46 [7,] 117 [8,]28 [9,]69 [10,]5 10 [11,]6 11 [12,] 18 12 [13,]9 13 [14,] 16 14 [15,] 18 15 [16,]9 16 [17,]2 17 [18,]7 18 [19,] 15 19 [20,]7 20 optA perm [1,] 131 [2,] 122 [3,]73 [4,]46 [5,]28 [6,]2 17 On Fri, May 31, 2013 at 2:02 PM, Laz lmra...@ufl.edu mailto:lmra...@ufl.edu wrote: Dear R Users, I created a function which returns a value every time it's run (A simplified toy example is attached on this mail). For example spat(a,b,c,d) # run the first time and it gives you ans1= 10, perm=1 ; run the second time and gives you ans2= 7, perm=2 etc I store both the result and the iteration on a matrix called vector with columns:1==ans, column2==permutation The rule I want to implement is: compare between ans1 and ans2. If ans1ans2, keep both ans1 and ans2. if ans1ans2, drop the whole row of the second permutation (that is drop both ans2 and perm2 but continue counting all permutations). Re-run the function for the 3rd time and repeat comparison between the value of the last run and the current value obtained. Return matrix ans with the saved ans and their permutations and another full matrix with all results including the dropped ans and their permutation numbers. I need to repeat this process 1000 times but I am getting stuck below. See attached R code. The code below works only for the first 6 permutations. suppose I want 1000 permutations, where do I keep the loop? Example: Not a perfect code though it somehow works: testx-function(perm){ optA-c() #while(perm=2){ for (k in 1:perm){ #repeat { optA[k]-sample(1:1000,1,replace=TRUE) perm[k]-k } mat2-as.matrix(cbind(optA=optA,perm=perm)) result-mat2 lenm-nrow(result) if(result[1,1]=result[2,1]) result-result[1,] return(list(mat2=mat2,result=result)) #} if(perm2){ mat2-as.matrix(cbind(optA=optA,perm=perm))
Re: [R] R help on loops
On 07-06-2013, at 10:59, Laz lmra...@ufl.edu wrote: Dear R users, I am stuck here: My first function returns a vector of 5 values. In my second function, I want to repeat this, a number of times, say 10 so that I have 10 rows and five columns but I keep on getting errors. See the code and results below: optm -function(perm, verbose = FALSE) { trace-c() for (k in 1:perm){ trace[k]-Rspatswap(rhox=0.6,rhoy=0.6,sigmasqG=0.081,SsqR=1)[1] perm[k]-k mat-cbind(trace, perm = seq(perm)) } if (verbose){ cat(***starting matrix\n) print(mat) } # iterate till done while(nrow(mat) 1){ high - diff(mat[, 'trace']) 0 if (!any(high)) break # done # find which one to delete delete - which.max(high) + 1L mat - mat[-delete, ] newmat-apply(mat,2,mean)[1] sdm-sd(mat[,1]) sem-sdm/sqrt(nrow(mat)) maxv-mat[1,1] minv-mat[nrow(mat),1] } stats-cbind(average=newmat,sd=sdm,se=sem,min=minv,max=maxv) stats } test-optm(perm=20) test average sd se min max trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241 itn-function(it){ siml-matrix(NA,ncol=5,nrow=length(it)) for(g in 1:it){ siml[g]-optm(perm=20) } siml-cbind(siml=siml) siml } ans-itn(5) Warning messages: 1: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 2: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 3: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 4: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 5: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length ans [,1] [,2] [,3] [,4] [,5] [1,] 0.8874234 0.8861666 0.8880521 0.8870958 0.8876469 1. Not reproducible code. Where does function Rspatswap come from? 2. You have several errors in function itn: Argument it is a scalar: length(it) is 1. You need to do siml - matrix(NA,ncol=5,nrow=it) Next in the g-loop you want to fill row g so do: siml[g,] - ….. Finally why are you doing siml - cbind(siml=siml)? Seems superfluous to me. Delete the line. Berend __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] R help on loops
Dear Berend, For reproducibility, Rspatswap() is a function which originally returns a single value. For example Rspatswap(...) and you get 0.8 So, run Rspatswap() 20 times and store all the values. Then from these 20 values, calculate the calculate average, sd,se,min,max to get something similar to: average sd se min max trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241 If we repeat the function 10 times, then I expect 10 rows with 5 columns but it does not work ? I hope I am now clearer... On 6/7/2013 5:24 AM, Berend Hasselman wrote: On 07-06-2013, at 10:59, Laz lmra...@ufl.edu wrote: Dear R users, I am stuck here: My first function returns a vector of 5 values. In my second function, I want to repeat this, a number of times, say 10 so that I have 10 rows and five columns but I keep on getting errors. See the code and results below: optm -function(perm, verbose = FALSE) { trace-c() for (k in 1:perm){ trace[k]-Rspatswap(rhox=0.6,rhoy=0.6,sigmasqG=0.081,SsqR=1)[1] perm[k]-k mat-cbind(trace, perm = seq(perm)) } if (verbose){ cat(***starting matrix\n) print(mat) } # iterate till done while(nrow(mat) 1){ high - diff(mat[, 'trace']) 0 if (!any(high)) break # done # find which one to delete delete - which.max(high) + 1L mat - mat[-delete, ] newmat-apply(mat,2,mean)[1] sdm-sd(mat[,1]) sem-sdm/sqrt(nrow(mat)) maxv-mat[1,1] minv-mat[nrow(mat),1] } stats-cbind(average=newmat,sd=sdm,se=sem,min=minv,max=maxv) stats } test-optm(perm=20) test average sd se min max trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241 itn-function(it){ siml-matrix(NA,ncol=5,nrow=length(it)) for(g in 1:it){ siml[g]-optm(perm=20) } siml-cbind(siml=siml) siml } ans-itn(5) Warning messages: 1: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 2: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 3: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 4: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 5: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length ans [,1] [,2] [,3] [,4] [,5] [1,] 0.8874234 0.8861666 0.8880521 0.8870958 0.8876469 1. Not reproducible code. Where does function Rspatswap come from? 2. You have several errors in function itn: Argument it is a scalar: length(it) is 1. You need to do siml - matrix(NA,ncol=5,nrow=it) Next in the g-loop you want to fill row g so do: siml[g,] - ….. Finally why are you doing siml - cbind(siml=siml)? Seems superfluous to me. Delete the line. Berend __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] R help on loops
Hi, I am almost getting there, but still have errors. Thanks for your help. I have tried improving but I get the following errors below: itn-function(it){ +siml-matrix(NA,ncol=5,nrow=it) +for(g in 1:it){ +siml[g]-optm(perm=20)[g] +} +siml +} itn(3) [,1] [,2] [,3] [,4] [,5] [1,] 0.8873775898 NA NA NA NA [2,] 0.0015584824 NA NA NA NA [3,] 0.0001414317 NA NA NA NA itn-function(it){ +siml-matrix(NA,ncol=5,nrow=it) +for(g in 1:it){ +siml[g]-optm(perm=20) +} +siml +} itn(3) [,1] [,2] [,3] [,4] [,5] [1,] 0.8880941 NA NA NA NA [2,] 0.8869727 NA NA NA NA [3,] 0.8877045 NA NA NA NA Warning messages: 1: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 2: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 3: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length I expect something close to average sd se min max 0.8881969 0.0008215379 0.000410769 0.8873842 0.8890167 0.884659 0.0004215379 0.000410769 0.2342 0.676307 0.8885839 0.0001215379 0.0002112 0.82752992 0.8836337 Thanks fpr you help. On 6/7/2013 5:24 AM, Berend Hasselman wrote: On 07-06-2013, at 10:59, Laz lmra...@ufl.edu wrote: Dear R users, I am stuck here: My first function returns a vector of 5 values. In my second function, I want to repeat this, a number of times, say 10 so that I have 10 rows and five columns but I keep on getting errors. See the code and results below: optm -function(perm, verbose = FALSE) { trace-c() for (k in 1:perm){ trace[k]-Rspatswap(rhox=0.6,rhoy=0.6,sigmasqG=0.081,SsqR=1)[1] perm[k]-k mat-cbind(trace, perm = seq(perm)) } if (verbose){ cat(***starting matrix\n) print(mat) } # iterate till done while(nrow(mat) 1){ high - diff(mat[, 'trace']) 0 if (!any(high)) break # done # find which one to delete delete - which.max(high) + 1L mat - mat[-delete, ] newmat-apply(mat,2,mean)[1] sdm-sd(mat[,1]) sem-sdm/sqrt(nrow(mat)) maxv-mat[1,1] minv-mat[nrow(mat),1] } stats-cbind(average=newmat,sd=sdm,se=sem,min=minv,max=maxv) stats } test-optm(perm=20) test average sd se min max trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241 itn-function(it){ siml-matrix(NA,ncol=5,nrow=length(it)) for(g in 1:it){ siml[g]-optm(perm=20) } siml-cbind(siml=siml) siml } ans-itn(5) Warning messages: 1: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 2: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 3: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 4: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 5: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length ans [,1] [,2] [,3] [,4] [,5] [1,] 0.8874234 0.8861666 0.8880521 0.8870958 0.8876469 1. Not reproducible code. Where does function Rspatswap come from? 2. You have several errors in function itn: Argument it is a scalar: length(it) is 1. You need to do siml - matrix(NA,ncol=5,nrow=it) Next in the g-loop you want to fill row g so do: siml[g,] - .. Finally why are you doing siml - cbind(siml=siml)? Seems superfluous to me. Delete the line. Berend [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] R help on loops
On 07-06-2013, at 11:57, Laz lmra...@ufl.edu wrote: Dear Berend, I have made some changes but I still get errors: For reproducibility, Rspatswap() is a function which originally returns a single value. For example Rspatswap(...) and you get 0.8 So, run Rspatswap() 20 times and store all the values. Then from these 20 values, calculate the calculate average, sd,se,min,max to get something similar to: average sd se min max trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241 If we repeat the function 10 times, then I expect 10 rows with 5 columns but it does not work ? Replacing Rspatswap(…)[1] with runif(1) (you could/should have done that to provide reproducible code) and the modifications I suggested you make in your function itn() like this itn-function(it){ siml-matrix(NA,ncol=5,nrow=it) for(g in 1:it){ siml[g,]-optm(perm=20) } siml } running itn(10) I get a matrix with 10 rows and 5 columns. So what do you mean by it does not work? You sometimes get an error message from apply due to a bad dim() like this Error in apply(mat, 2, mean) : dim(X) must have a positive length When the result of mat[-delete,] is a matrix with a single row the result is simplified to a vector. See ?[ in particular the drop argument. So this should work in function optm() mat - mat[-delete,, drop=FALSE] Berend __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] R help on loops
Please, please do not use html formatted mail. It is clearly requested by the mailing list The code of your last mail is a mess and when replying it becomes even more of a mess. I told you to do siml[g,] - optm(perm=20) See the comma after g. and not what you are now doing with siml[g]-optm(perm=20)[g] I'm giving up. Berend On 07-06-2013, at 12:15, Laz lmra...@ufl.edu wrote: Hi, I am almost getting there, but still have errors. Thanks for your help. I have tried improving but I get the following errors below: itn-function(it){ + siml-matrix(NA,ncol=5,nrow=it) + for(g in 1:it){ + siml[g]-optm(perm=20)[g] + } + siml + } itn(3) [,1] [,2] [,3] [,4] [,5] [1,] 0.8873775898 NA NA NA NA [2,] 0.0015584824 NA NA NA NA [3,] 0.0001414317 NA NA NA NA itn-function(it){ + siml-matrix(NA,ncol=5,nrow=it) + for(g in 1:it){ + siml[g]-optm(perm=20) + } + siml + } itn(3) [,1] [,2] [,3] [,4] [,5] [1,] 0.8880941 NA NA NA NA [2,] 0.8869727 NA NA NA NA [3,] 0.8877045 NA NA NA NA Warning messages: 1: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 2: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 3: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length I expect something close to average sd se min max 0.8881969 0.0008215379 0.000410769 0.8873842 0.8890167 0.884659 0.0004215379 0.000410769 0.2342 0.676307 0.8885839 0.0001215379 0.0002112 0.82752992 0.8836337 Thanks fpr you help. On 6/7/2013 5:24 AM, Berend Hasselman wrote: On 07-06-2013, at 10:59, Laz lmra...@ufl.edu wrote: Dear R users, I am stuck here: My first function returns a vector of 5 values. In my second function, I want to repeat this, a number of times, say 10 so that I have 10 rows and five columns but I keep on getting errors. See the code and results below: optm -function(perm, verbose = FALSE) { trace-c() for (k in 1:perm){ trace[k]-Rspatswap(rhox=0.6,rhoy=0.6,sigmasqG=0.081,SsqR=1)[1] perm[k]-k mat-cbind(trace, perm = seq(perm)) } if (verbose){ cat(***starting matrix\n) print(mat) } # iterate till done while(nrow(mat) 1){ high - diff(mat[, 'trace']) 0 if (!any(high)) break # done # find which one to delete delete - which.max(high) + 1L mat - mat[-delete, ] newmat-apply(mat,2,mean)[1] sdm-sd(mat[,1]) sem-sdm/sqrt(nrow(mat)) maxv-mat[1,1] minv-mat[nrow(mat),1] } stats-cbind(average=newmat,sd=sdm,se=sem,min=minv,max=maxv) stats } test-optm(perm=20) test average sd se min max trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241 itn-function(it){ siml-matrix(NA,ncol=5,nrow=length(it)) for(g in 1:it){ siml[g]-optm(perm=20) } siml-cbind(siml=siml) siml } ans-itn(5) Warning messages: 1: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 2: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 3: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 4: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length 5: In siml[g] - optm(perm = 20) : number of items to replace is not a multiple of replacement length ans [,1] [,2] [,3] [,4] [,5] [1,] 0.8874234 0.8861666 0.8880521 0.8870958 0.8876469 1. Not reproducible code. Where does function Rspatswap come from? 2. You have several errors in function itn: Argument it is a scalar: length(it) is 1. You need to do siml - matrix(NA,ncol=5,nrow=it) Next in the g-loop you want to fill row g so do: siml[g,] - ….. Finally why are you doing siml - cbind(siml=siml)? Seems superfluous to me. Delete the line. Berend __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] R help on loops
Dear R Users, I created a function which returns a value every time it's run (A simplified toy example is attached on this mail). For example spat(a,b,c,d) # run the first time and it gives you ans1= 10, perm=1 ; run the second time and gives you ans2= 7, perm=2 etc I store both the result and the iteration on a matrix called vector with columns:1==ans, column2==permutation The rule I want to implement is: compare between ans1 and ans2. If ans1ans2, keep both ans1 and ans2. if ans1ans2, drop the whole row of the second permutation (that is drop both ans2 and perm2 but continue counting all permutations). Re-run the function for the 3rd time and repeat comparison between the value of the last run and the current value obtained. Return matrix ans with the saved ans and their permutations and another full matrix with all results including the dropped ans and their permutation numbers. I need to repeat this process 1000 times but I am getting stuck below. See attached R code. The code below works only for the first 6 permutations. suppose I want 1000 permutations, where do I keep the loop? Example: Not a perfect code though it somehow works: testx-function(perm){ optA-c() #while(perm=2){ for (k in 1:perm){ #repeat { optA[k]-sample(1:1000,1,replace=TRUE) perm[k]-k } mat2-as.matrix(cbind(optA=optA,perm=perm)) result-mat2 lenm-nrow(result) if(result[1,1]=result[2,1]) result-result[1,] return(list(mat2=mat2,result=result)) #} if(perm2){ mat2-as.matrix(cbind(optA=optA,perm=perm)) result-mat2 lenm-nrow(result) if(result[1,1]=result[2,1]) result-result[1,] if(result[lenm-1,1]=result[lenm,1]) result-result[-lenm,] if(result[(lenm-2),1]=result[(lenm-1),1]) result-result[-(lenm-1),] if(result[(lenm-3),1]=result[(lenm-2),1]) result-result[-(lenm-2),] if(result[(lenm-4),1]=result[(lenm-3),1]) result-result[-(lenm-3),] if(result[(lenm-5),1]=result[(lenm-4),1]) result-result[-(lenm-4),] return(list(mat2=mat2,result=result)) } } ## Now calling my function below: testx(perm=6) $mat2 optA perm [1,] 2721 [2,] 8582 [3,] 8343 [4,] 8624 [5,] 6505 [6,] 4056 $result optA perm 2721 testx(perm=2) $mat2 optA perm [1,] 3981 [2,] 8162 $result optA perm 3981 [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] R help on loops
Is this what you want? I was not clear on your algorithm, but is looks like you wanted descending values: testx - + function(n, verbose = FALSE) + { + mat - cbind(optA = sample(n, n, TRUE), perm = seq(n)) + if (verbose){ + cat(***starting matrix\n) + print(mat) + } + # iterate till done + while(nrow(mat) 1){ + high - diff(mat[, 'optA']) 0 + if (!any(high)) break # done + # find which one to delete + delete - which.max(high) + 1L + mat - mat[-delete, ] + } + mat + } testx(20, verbose = TRUE) ***starting matrix optA perm [1,] 131 [2,] 122 [3,]73 [4,] 104 [5,] 115 [6,]46 [7,] 117 [8,]28 [9,]69 [10,]5 10 [11,]6 11 [12,] 18 12 [13,]9 13 [14,] 16 14 [15,] 18 15 [16,]9 16 [17,]2 17 [18,]7 18 [19,] 15 19 [20,]7 20 optA perm [1,] 131 [2,] 122 [3,]73 [4,]46 [5,]28 [6,]2 17 On Fri, May 31, 2013 at 2:02 PM, Laz lmra...@ufl.edu wrote: Dear R Users, I created a function which returns a value every time it's run (A simplified toy example is attached on this mail). For example spat(a,b,c,d) # run the first time and it gives you ans1= 10, perm=1 ; run the second time and gives you ans2= 7, perm=2 etc I store both the result and the iteration on a matrix called vector with columns:1==ans, column2==permutation The rule I want to implement is: compare between ans1 and ans2. If ans1ans2, keep both ans1 and ans2. if ans1ans2, drop the whole row of the second permutation (that is drop both ans2 and perm2 but continue counting all permutations). Re-run the function for the 3rd time and repeat comparison between the value of the last run and the current value obtained. Return matrix ans with the saved ans and their permutations and another full matrix with all results including the dropped ans and their permutation numbers. I need to repeat this process 1000 times but I am getting stuck below. See attached R code. The code below works only for the first 6 permutations. suppose I want 1000 permutations, where do I keep the loop? Example: Not a perfect code though it somehow works: testx-function(perm){ optA-c() #while(perm=2){ for (k in 1:perm){ #repeat { optA[k]-sample(1:1000,1,replace=TRUE) perm[k]-k } mat2-as.matrix(cbind(optA=optA,perm=perm)) result-mat2 lenm-nrow(result) if(result[1,1]=result[2,1]) result-result[1,] return(list(mat2=mat2,result=result)) #} if(perm2){ mat2-as.matrix(cbind(optA=optA,perm=perm)) result-mat2 lenm-nrow(result) if(result[1,1]=result[2,1]) result-result[1,] if(result[lenm-1,1]=result[lenm,1]) result-result[-lenm,] if(result[(lenm-2),1]=result[(lenm-1),1]) result-result[-(lenm-1),] if(result[(lenm-3),1]=result[(lenm-2),1]) result-result[-(lenm-2),] if(result[(lenm-4),1]=result[(lenm-3),1]) result-result[-(lenm-3),] if(result[(lenm-5),1]=result[(lenm-4),1]) result-result[-(lenm-4),] return(list(mat2=mat2,result=result)) } } ## Now calling my function below: testx(perm=6) $mat2 optA perm [1,] 2721 [2,] 8582 [3,] 8343 [4,] 8624 [5,] 6505 [6,] 4056 $result optA perm 2721 testx(perm=2) $mat2 optA perm [1,] 3981 [2,] 8162 $result optA perm 3981 [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- Jim Holtman Data Munger Guru What is the problem that you are trying to solve? Tell me what you want to do, not how you want to do it. [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with loops
On 08/11/2011 07:51 PM, William Dunlap wrote: -Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of R. Michael Weylandt Sent: Thursday, August 11, 2011 10:09 AM To: Srinivas Iyyer Cc: r-help@r-project.org Subject: Re: [R] help with loops No problem, By the way, you can't (or at least shouldn't) use return() outside of a function -- that was the source of your old error message. If you, for whatever reason, couldn't use unlist() you would write: OurUnlist - function(c, unique = F) { if (!is.list(c)) return(c) z - NULL for (i in seq_along(c)) { z - c(z,c[[i]]) } if (unique) return(unique(z)) return(z) } or some such. Still, I suggest you stick with built in functions whenever possible. I tend to encourage people to write functions. In addition, writing functions yourself is a good way to exercise your R skills. On the other hand, built in functions often solve the problem faster and are more generic. In my experience it takes quite a bit of R knowledge before one is good enough to beat a general, builtin function. Often a lengthy self written function can be replaced by one call to a built in function. In addition, it saves a lot of time when you use the already present functions. Several times I wanted something done in R, only to find out that it was already done. This meant getting the job done in 1 hour instead of two days of programming. In general I tend to agree with Michael and encourage people to stick with the builtin functions. my 2 cts ;), regards, Paul I suppose you may end up reinventing the wheel, but once you get used to writing functions it is often faster to write a specialized one than to find one that meets your needs. When you discover a new idiom for your task (e.g., calling unlist() instead of the for loop), you just edit one function (OurUnlist) instead of editing all your scripts that used the old idiom). Once you get used to writing functions (and using them), you are ready to document them and package them up for others to use. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com Michael Weylandt PS -- Can you email me (off list) and let me know what this is for? We've been asked this question a couple of times over the last few days and I'm just wondering why it's a calculation of interest to so many. On Thu, Aug 11, 2011 at 1:00 PM, Srinivas Iyyer srini_iyyer_...@yahoo.comwrote: Thank you. that was very easy. -srini --- On *Thu, 8/11/11, R. Michael Weylandt michael.weyla...@gmail.com*wrote: From: R. Michael Weylandt michael.weyla...@gmail.com Subject: Re: [R] help with loops To: Srinivas Iyyer srini_iyyer_...@yahoo.com Cc: r-help@r-project.org Date: Thursday, August 11, 2011, 12:49 PM unlist() Michael Weylandt On Thu, Aug 11, 2011 at 12:46 PM, Srinivas Iyyer srini_iyyer_...@yahoo.com http://mc/compose?to=srini_iyyer_...@yahoo.com wrote: hi I need help with list object. I have a list object a - c('apple','orange','grape') b - c('car','truck','jeep') c - list(a,b) names(c) - c('fruit','vehicle') c $fruit [1] apple orange grape $vehicle [1] car truck jeep I want to write all the elements of this list in one object 'z'. z [1] apple orange grape car truck jeep How can I write the elements of c to z I tried using a for loop. Could any one help me please. thanks z - '' for (i in 1:length(c)){ + k - c[[i]] + z - c(z,k) + return(z)} Error: no function to return from, jumping to top level Thank you. srini __ R-help@r-project.org http://mc/compose?to=R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- Paul Hiemstra, Ph.D. Global Climate Division Royal Netherlands Meteorological Institute (KNMI) Wilhelminalaan 10 | 3732 GK | De Bilt | Kamer B 3.39 P.O. Box 201 | 3730 AE | De Bilt tel: +31 30 2206 494 http://intamap.geo.uu.nl/~paul http://nl.linkedin.com/pub/paul-hiemstra/20/30b/770 __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http
[R] help with loops
hi I need help with list object. I have a list object a - c('apple','orange','grape') b - c('car','truck','jeep') c - list(a,b) names(c) - c('fruit','vehicle') c $fruit [1] apple orange grape $vehicle [1] car truck jeep I want to write all the elements of this list in one object 'z'. z [1] apple orange grape car truck jeep How can I write the elements of c to z I tried using a for loop. Could any one help me please. thanks z - '' for (i in 1:length(c)){ + k - c[[i]] + z - c(z,k) + return(z)} Error: no function to return from, jumping to top level Thank you. srini __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with loops
unlist() Michael Weylandt On Thu, Aug 11, 2011 at 12:46 PM, Srinivas Iyyer srini_iyyer_...@yahoo.comwrote: hi I need help with list object. I have a list object a - c('apple','orange','grape') b - c('car','truck','jeep') c - list(a,b) names(c) - c('fruit','vehicle') c $fruit [1] apple orange grape $vehicle [1] car truck jeep I want to write all the elements of this list in one object 'z'. z [1] apple orange grape car truck jeep How can I write the elements of c to z I tried using a for loop. Could any one help me please. thanks z - '' for (i in 1:length(c)){ + k - c[[i]] + z - c(z,k) + return(z)} Error: no function to return from, jumping to top level Thank you. srini __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with loops
Thank you. that was very easy. -srini --- On Thu, 8/11/11, R. Michael Weylandt michael.weyla...@gmail.com wrote: From: R. Michael Weylandt michael.weyla...@gmail.com Subject: Re: [R] help with loops To: Srinivas Iyyer srini_iyyer_...@yahoo.com Cc: r-help@r-project.org Date: Thursday, August 11, 2011, 12:49 PM unlist() Michael Weylandt On Thu, Aug 11, 2011 at 12:46 PM, Srinivas Iyyer srini_iyyer_...@yahoo.com wrote: hi I need help with list object. I have a list object a - c('apple','orange','grape') b - c('car','truck','jeep') c - list(a,b) names(c) - c('fruit','vehicle') c $fruit [1] apple orange grape $vehicle [1] car truck jeep I want to write all the elements of this list in one object 'z'. z [1] apple orange grape car truck jeep How can I write the elements of c to z I tried using a for loop. Could any one help me please. thanks z - '' for (i in 1:length(c)){ + k - c[[i]] + z - c(z,k) + return(z)} Error: no function to return from, jumping to top level Thank you. srini __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with loops
No problem, By the way, you can't (or at least shouldn't) use return() outside of a function -- that was the source of your old error message. If you, for whatever reason, couldn't use unlist() you would write: OurUnlist - function(c, unique = F) { if (!is.list(c)) return(c) z - NULL for (i in seq_along(c)) { z - c(z,c[[i]]) } if (unique) return(unique(z)) return(z) } or some such. Still, I suggest you stick with built in functions whenever possible. Michael Weylandt PS -- Can you email me (off list) and let me know what this is for? We've been asked this question a couple of times over the last few days and I'm just wondering why it's a calculation of interest to so many. On Thu, Aug 11, 2011 at 1:00 PM, Srinivas Iyyer srini_iyyer_...@yahoo.comwrote: Thank you. that was very easy. -srini --- On *Thu, 8/11/11, R. Michael Weylandt michael.weyla...@gmail.com*wrote: From: R. Michael Weylandt michael.weyla...@gmail.com Subject: Re: [R] help with loops To: Srinivas Iyyer srini_iyyer_...@yahoo.com Cc: r-help@r-project.org Date: Thursday, August 11, 2011, 12:49 PM unlist() Michael Weylandt On Thu, Aug 11, 2011 at 12:46 PM, Srinivas Iyyer srini_iyyer_...@yahoo.com http://mc/compose?to=srini_iyyer_...@yahoo.com wrote: hi I need help with list object. I have a list object a - c('apple','orange','grape') b - c('car','truck','jeep') c - list(a,b) names(c) - c('fruit','vehicle') c $fruit [1] apple orange grape $vehicle [1] car truck jeep I want to write all the elements of this list in one object 'z'. z [1] apple orange grape car truck jeep How can I write the elements of c to z I tried using a for loop. Could any one help me please. thanks z - '' for (i in 1:length(c)){ + k - c[[i]] + z - c(z,k) + return(z)} Error: no function to return from, jumping to top level Thank you. srini __ R-help@r-project.org http://mc/compose?to=R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with loops
-Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of R. Michael Weylandt Sent: Thursday, August 11, 2011 10:09 AM To: Srinivas Iyyer Cc: r-help@r-project.org Subject: Re: [R] help with loops No problem, By the way, you can't (or at least shouldn't) use return() outside of a function -- that was the source of your old error message. If you, for whatever reason, couldn't use unlist() you would write: OurUnlist - function(c, unique = F) { if (!is.list(c)) return(c) z - NULL for (i in seq_along(c)) { z - c(z,c[[i]]) } if (unique) return(unique(z)) return(z) } or some such. Still, I suggest you stick with built in functions whenever possible. I tend to encourage people to write functions. I suppose you may end up reinventing the wheel, but once you get used to writing functions it is often faster to write a specialized one than to find one that meets your needs. When you discover a new idiom for your task (e.g., calling unlist() instead of the for loop), you just edit one function (OurUnlist) instead of editing all your scripts that used the old idiom). Once you get used to writing functions (and using them), you are ready to document them and package them up for others to use. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com Michael Weylandt PS -- Can you email me (off list) and let me know what this is for? We've been asked this question a couple of times over the last few days and I'm just wondering why it's a calculation of interest to so many. On Thu, Aug 11, 2011 at 1:00 PM, Srinivas Iyyer srini_iyyer_...@yahoo.comwrote: Thank you. that was very easy. -srini --- On *Thu, 8/11/11, R. Michael Weylandt michael.weyla...@gmail.com*wrote: From: R. Michael Weylandt michael.weyla...@gmail.com Subject: Re: [R] help with loops To: Srinivas Iyyer srini_iyyer_...@yahoo.com Cc: r-help@r-project.org Date: Thursday, August 11, 2011, 12:49 PM unlist() Michael Weylandt On Thu, Aug 11, 2011 at 12:46 PM, Srinivas Iyyer srini_iyyer_...@yahoo.com http://mc/compose?to=srini_iyyer_...@yahoo.com wrote: hi I need help with list object. I have a list object a - c('apple','orange','grape') b - c('car','truck','jeep') c - list(a,b) names(c) - c('fruit','vehicle') c $fruit [1] apple orange grape $vehicle [1] car truck jeep I want to write all the elements of this list in one object 'z'. z [1] apple orange grape car truck jeep How can I write the elements of c to z I tried using a for loop. Could any one help me please. thanks z - '' for (i in 1:length(c)){ + k - c[[i]] + z - c(z,k) + return(z)} Error: no function to return from, jumping to top level Thank you. srini __ R-help@r-project.org http://mc/compose?to=R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help on loops
Thanks Jim! --- On Tue, 12/7/10, jim holtman jholt...@gmail.com wrote: From: jim holtman jholt...@gmail.com Subject: Re: [R] Help on loops To: Anup Nandialath anup_nandial...@yahoo.com Cc: r-help@r-project.org Date: Tuesday, December 7, 2010, 7:47 PM use split and lapply to make it easier. Substitute in your own calculations since this is just an example: x id t X1 X2 1 1 1 4 3 2 1 2 9 2 3 1 3 7 3 4 1 4 6 6 5 2 1 6 4 6 2 2 5 3 7 2 3 1 1 8 3 1 9 6 9 3 2 5 5 # first split the data by 'id' x.s - split(x, x$id) # then process each group result - lapply(x.s, function(.grp){ + output - .grp[1, 3:4] * 4 # data from the first row + i - 2 + # repeat for the rest of the row + while (i = nrow(.grp)){ + output - output + .grp[i, 3:4] * 2 + i - i + 1 + } + output # return value + }) result $`1` X1 X2 1 60 34 $`2` X1 X2 5 36 24 $`3` X1 X2 8 46 34 On Tue, Dec 7, 2010 at 5:43 PM, Anup Nandialath anup_nandial...@yahoo.com wrote: Dear R-helpers, I have a basic question on using loops. I have a panel data set with different variables measured for n firms over t time periods. A snapshot of the data is given below id t X1 X2 1 1 4 3 1 2 9 2 1 3 7 3 1 4 6 6 2 1 6 4 2 2 5 3 2 3 1 1 3 1 9 6 3 2 5 5 thus total sample n=9 My problem is as follows. I need to do some computations on the data where the first observation for each firm (ie. id=1 and t=1; id=2 and t=1; id=3 and t=1) requires a specific operation on x1 and x2 and the subsequent operations are based on the computed value of the first operation. For example the pseudocode is as follows ##define output matrix output - rep(0,n) ## define coefficient vector b - c(1,1) for (i in 1:number of simulations) { for (j in 1:id) { for(k in 1:t) { if(Data$t[,2]==1) { meanvec - Data[k,3:4]%*%b output[k] = calc (meanvec) # output from calc is a scalar } else output[k]= calc(a*output[k-1]+Data[k,3:4]%*%b) } } } Thus the end result should be a vector output with nine observations based on the computations. I hope the problem is clear and I greatly appreciate any help in solving this problem . Thanks in advance for your help. Kind Regards Anup [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- Jim Holtman Data Munger Guru What is the problem that you are trying to solve? [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Help on loops
Dear R-helpers, I have a basic question on using loops. I have a panel data set with different variables measured for n firms over t time periods. A snapshot of the data is given below id t X1 X2 1 1 4 3 1 2 9 2 1 3 7 3 1 4 6 6 2 1 6 4 2 2 5 3 2 3 1 1 3 1 9 6 3 2 5 5 thus total sample n=9 My problem is as follows. I need to do some computations on the data where the first observation for each firm (ie. id=1 and t=1; id=2 and t=1; id=3 and t=1) requires a specific operation on x1 and x2 and the subsequent operations are based on the computed value of the first operation. For example the pseudocode is as follows ##define output matrix output - rep(0,n) ## define coefficient vector b - c(1,1) for (i in 1:number of simulations) { for (j in 1:id) { for(k in 1:t) { if(Data$t[,2]==1) { meanvec - Data[k,3:4]%*%b output[k] = calc (meanvec) # output from calc is a scalar } else output[k]= calc(a*output[k-1]+Data[k,3:4]%*%b) } } } Thus the end result should be a vector output with nine observations based on the computations. I hope the problem is clear and I greatly appreciate any help in solving this problem . Thanks in advance for your help. Kind Regards Anup [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help on loops
use split and lapply to make it easier. Substitute in your own calculations since this is just an example: x id t X1 X2 1 1 1 4 3 2 1 2 9 2 3 1 3 7 3 4 1 4 6 6 5 2 1 6 4 6 2 2 5 3 7 2 3 1 1 8 3 1 9 6 9 3 2 5 5 # first split the data by 'id' x.s - split(x, x$id) # then process each group result - lapply(x.s, function(.grp){ + output - .grp[1, 3:4] * 4 # data from the first row + i - 2 + # repeat for the rest of the row + while (i = nrow(.grp)){ + output - output + .grp[i, 3:4] * 2 + i - i + 1 + } + output # return value + }) result $`1` X1 X2 1 60 34 $`2` X1 X2 5 36 24 $`3` X1 X2 8 46 34 On Tue, Dec 7, 2010 at 5:43 PM, Anup Nandialath anup_nandial...@yahoo.com wrote: Dear R-helpers, I have a basic question on using loops. I have a panel data set with different variables measured for n firms over t time periods. A snapshot of the data is given below id t X1 X2 1 1 4 3 1 2 9 2 1 3 7 3 1 4 6 6 2 1 6 4 2 2 5 3 2 3 1 1 3 1 9 6 3 2 5 5 thus total sample n=9 My problem is as follows. I need to do some computations on the data where the first observation for each firm (ie. id=1 and t=1; id=2 and t=1; id=3 and t=1) requires a specific operation on x1 and x2 and the subsequent operations are based on the computed value of the first operation. For example the pseudocode is as follows ##define output matrix output - rep(0,n) ## define coefficient vector b - c(1,1) for (i in 1:number of simulations) { for (j in 1:id) { for(k in 1:t) { if(Data$t[,2]==1) { meanvec - Data[k,3:4]%*%b output[k] = calc (meanvec) # output from calc is a scalar } else output[k]= calc(a*output[k-1]+Data[k,3:4]%*%b) } } } Thus the end result should be a vector output with nine observations based on the computations. I hope the problem is clear and I greatly appreciate any help in solving this problem . Thanks in advance for your help. Kind Regards Anup [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- Jim Holtman Data Munger Guru What is the problem that you are trying to solve? __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Help with Loops
Hi I have tried many attempts but cant get the loop right, as I am not a strong programmer. What I am basically trying to do is compare 2 spreadsheets. The problem is that one of them only contain a portion of the overall data (TESTSAMP), where the other has a full datasetFULLSAMP. From the complete set I would like to remove the rows of data which are not in the TESTSAMP. Column 1 contains the sample numbers which can be used to identify samples. Does anyone have any suggestions? I have tried various things like double loops and so on, but I am sure there is an easier way or function to do this. i tried this method, but Im not sure how to only keep looping until a match is found. I dont understand how repeat loops work in R. for (i in 1:length(FULLSAMP[,1])) { if (FULLSAMP[i,1] != TESTSAMP[i,1]) { FULLSAMP - FULLSAMP[-i,] } Thanks in advance __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help with Loops
You don't need a loop for this, I think. Since you don't provide an example it's hard to know how your data are set up, but look at this: FULLSAMP - data.frame(A = 1:10, B=letters[1:10]) TESTSAMP - data.frame(A = c(2,4,5,8), C=1:4) FULLSAMP A B 1 1 a 2 2 b 3 3 c 4 4 d 5 5 e 6 6 f 7 7 g 8 8 h 9 9 i 10 10 j TESTSAMP A C 1 2 1 2 4 2 3 5 3 4 8 4 FULLSAMP[FULLSAMP$A %in% TESTSAMP$A,] A B 2 2 b 4 4 d 5 5 e 8 8 h Sarah On Thu, May 13, 2010 at 10:49 AM, Amit Patel amitrh...@yahoo.co.uk wrote: Hi I have tried many attempts but cant get the loop right, as I am not a strong programmer. What I am basically trying to do is compare 2 spreadsheets. The problem is that one of them only contain a portion of the overall data (TESTSAMP), where the other has a full datasetFULLSAMP. From the complete set I would like to remove the rows of data which are not in the TESTSAMP. Column 1 contains the sample numbers which can be used to identify samples. Does anyone have any suggestions? I have tried various things like double loops and so on, but I am sure there is an easier way or function to do this. i tried this method, but Im not sure how to only keep looping until a match is found. I dont understand how repeat loops work in R. for (i in 1:length(FULLSAMP[,1])) { if (FULLSAMP[i,1] != TESTSAMP[i,1]) { FULLSAMP - FULLSAMP[-i,] } Thanks in advance -- Sarah Goslee http://www.functionaldiversity.org __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help with Loops
Hi, On Thu, May 13, 2010 at 10:49 AM, Amit Patel amitrh...@yahoo.co.uk wrote: Hi I have tried many attempts but cant get the loop right, as I am not a strong programmer. What I am basically trying to do is compare 2 spreadsheets. The problem is that one of them only contain a portion of the overall data (TESTSAMP), where the other has a full datasetFULLSAMP. From the complete set I would like to remove the rows of data which are not in the TESTSAMP. Column 1 contains the sample numbers which can be used to identify samples. Does anyone have any suggestions? I have tried various things like double loops and so on, but I am sure there is an easier way or function to do this. i tried this method, but Im not sure how to only keep looping until a match is found. I dont understand how repeat loops work in R. for (i in 1:length(FULLSAMP[,1])) { if (FULLSAMP[i,1] != TESTSAMP[i,1]) { FULLSAMP - FULLSAMP[-i,] } You want to not use for loops as much as possible. Imagine your samples are identified as letters, so FULLSAMP[,1] will be letters A..Z, and TESTSAMP[,1] will be some random 15 letters. Now the job is to match the rows in TESTAMP to the rows in FULLSAMP, and remove any extra rows in FULLSAMP that don' appear in testamp. ## Making some data R fullsamp - data.frame(id=LETTERS, something=sample(1:100, length(letters)), stringsAsFactors=FALSE) R testsamp - data.frame(id=sample(LETTERS, 15), something=sample(1:100, 15), stringsAsFactors=FALSE) ## Let's find where the testamp rows appear in fullsamp R xref - match(testsamp[,1], fullsamp[,1]) ## Now reduce fullsamp to have only the data corresponding to testsamp ## (and in the same order R fullsamp.sub - fullsamp[xref,] Notice that fullsamp.sub now has only rows with IDs appearing in testsamp and they are also in the same order as testsamp. Now go ahead and read the help you'll find in ?match -steve -- Steve Lianoglou Graduate Student: Computational Systems Biology | Memorial Sloan-Kettering Cancer Center | Weill Medical College of Cornell University Contact Info: http://cbio.mskcc.org/~lianos/contact __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help with Loops
On May 13, 2010, at 10:49 AM, Amit Patel wrote: Hi I have tried many attempts but cant get the loop right, as I am not a strong programmer. What I am basically trying to do is compare 2 spreadsheets. The problem is that one of them only contain a portion of the overall data (TESTSAMP), where the other has a full datasetFULLSAMP. From the complete set I would like to remove the rows of data which are not in the TESTSAMP. Column 1 contains the sample numbers which can be used to identify samples. Does anyone have any suggestions? I have tried various things like double loops and so on, but I am sure there is an easier way or function to do this. i tried this method, but Im not sure how to only keep looping until a match is found. I dont understand how repeat loops work in R. for (i in 1:length(FULLSAMP[,1])) { if (FULLSAMP[i,1] != TESTSAMP[i,1]) { FULLSAMP - FULLSAMP[-i,] } Abandon the loop. Use merge. ... or the %in% function. -- David Winsemius, MD West Hartford, CT __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] help with loops
Hi guys, my doubt is quite simple, I´ll try to explain: test = matrix(0, nrow = 783, ncol = 12) for (x in 1:9){ for (y in 1:12){ ### In the original script for each y its generated a vector (87x1) ### 87 times 9(x) = 783 (equals the number of rows I want to fill in the test matrix } } What I would like to do is to fill the test matrix with the ys in the collumns and the 87 elements of each x in the rows. for example, x = 1 y = 1 test[1:87, 1] = vector generated when y is 1 x = 2 y = 1 test [88:174,1] = another vector generated when y is 2 Could anybody help me? The script is quite long so i couldn´t just paste it here I think what i wrote above is undestandable. Thank you very much -- View this message in context: http://www.nabble.com/help-with-loops-tp25898891p25898891.html Sent from the R help mailing list archive at Nabble.com. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Help with loops
Hi I am trying to create a loop which averages replicates in my data. The original data has many rows. and consists of 40 column zz[,2:41] plus row headings in zz[,1] I am trying to average each set of values (i.e. zz[1,2:3] averaged and placed in average_value[1,2] and so on. below is my script but it seems to be stuck in an endless loop Any suggestions?? for (i in 1:length(average_value[,1])) { average_value[i] - i^100; print(average_value[i]) #calculates Meanss #Sample A average_value[i,2] - rowMeans(zz[i,2:3]) average_value[i,3] - rowMeans(zz[i,4:5]) average_value[i,4] - rowMeans(zz[i,6:7]) average_value[i,5] - rowMeans(zz[i,8:9]) average_value[i,6] - rowMeans(zz[i,10:11]) #Sample B average_value[i,7] - rowMeans(zz[i,12:13]) average_value[i,8] - rowMeans(zz[i,14:15]) average_value[i,9] - rowMeans(zz[i,16:17]) average_value[i,10] - rowMeans(zz[i,18:19]) average_value[i,11] - rowMeans(zz[i,20:21]) #Sample C average_value[i,12] - rowMeans(zz[i,22:23]) average_value[i,13] - rowMeans(zz[i,24:25]) average_value[i,14] - rowMeans(zz[i,26:27]) average_value[i,15] - rowMeans(zz[i,28:29]) average_value[i,16] - rowMeans(zz[i,30:31]) #Sample D average_value[i,17] - rowMeans(zz[i,32:33]) average_value[i,18] - rowMeans(zz[i,34:35]) average_value[i,19] - rowMeans(zz[i,36:37]) average_value[i,20] - rowMeans(zz[i,38:39]) average_value[i,21] - rowMeans(zz[i,40:41]) } thanks __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help with loops
I'm not quite sure what you want to do, but this might help: d=data.frame(replicate(40, rnorm(20))) d$sample=rep(c('a','b','c','d'),each=5) lib(doBy) summaryBy(.~sample,da=d) David Freedman Amit Patel-7 wrote: Hi I am trying to create a loop which averages replicates in my data. The original data has many rows. and consists of 40 column zz[,2:41] plus row headings in zz[,1] I am trying to average each set of values (i.e. zz[1,2:3] averaged and placed in average_value[1,2] and so on. below is my script but it seems to be stuck in an endless loop Any suggestions?? for (i in 1:length(average_value[,1])) { average_value[i] - i^100; print(average_value[i]) #calculates Meanss #Sample A average_value[i,2] - rowMeans(zz[i,2:3]) average_value[i,3] - rowMeans(zz[i,4:5]) average_value[i,4] - rowMeans(zz[i,6:7]) average_value[i,5] - rowMeans(zz[i,8:9]) average_value[i,6] - rowMeans(zz[i,10:11]) #Sample B average_value[i,7] - rowMeans(zz[i,12:13]) average_value[i,8] - rowMeans(zz[i,14:15]) average_value[i,9] - rowMeans(zz[i,16:17]) average_value[i,10] - rowMeans(zz[i,18:19]) average_value[i,11] - rowMeans(zz[i,20:21]) #Sample C average_value[i,12] - rowMeans(zz[i,22:23]) average_value[i,13] - rowMeans(zz[i,24:25]) average_value[i,14] - rowMeans(zz[i,26:27]) average_value[i,15] - rowMeans(zz[i,28:29]) average_value[i,16] - rowMeans(zz[i,30:31]) #Sample D average_value[i,17] - rowMeans(zz[i,32:33]) average_value[i,18] - rowMeans(zz[i,34:35]) average_value[i,19] - rowMeans(zz[i,36:37]) average_value[i,20] - rowMeans(zz[i,38:39]) average_value[i,21] - rowMeans(zz[i,40:41]) } thanks __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- View this message in context: http://www.nabble.com/Help-with-loops-tp23558647p23560599.html Sent from the R help mailing list archive at Nabble.com. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help with loops
Dear Amit, The following should get you started. What I'm doing is creating an identifiers (g) with the names of the columns you want to group for and then use a combination of apply() and tapply() to get the mean for each row in the levels of g. In your case, you have more columns than I have in my example, but with slightly modifications you can adapt the code below to your needs. See ?apply and ?rep for more information. HTH, Jorge # Some data set.seed(123) X - matrix(rnorm(100), ncol=10) colnames(X) - paste('x',1:10,sep=) rownames(X) - paste('sample_',1:10,sep=) # Defining the groups using seq() g - rep(1:(ncol(X)/2), each = 2 ) # Calculating the means res - t( apply(X, 1, tapply, g, mean) ) res # res[1,1] is the mean for X[1, 1:2] mean(X[1,1:2]) # [1] 0.2408457 On Fri, May 15, 2009 at 8:17 AM, Amit Patel amitrh...@yahoo.co.uk wrote: Hi I am trying to create a loop which averages replicates in my data. The original data has many rows. and consists of 40 column zz[,2:41] plus row headings in zz[,1] I am trying to average each set of values (i.e. zz[1,2:3] averaged and placed in average_value[1,2] and so on. below is my script but it seems to be stuck in an endless loop Any suggestions?? for (i in 1:length(average_value[,1])) { average_value[i] - i^100; print(average_value[i]) #calculates Meanss #Sample A average_value[i,2] - rowMeans(zz[i,2:3]) average_value[i,3] - rowMeans(zz[i,4:5]) average_value[i,4] - rowMeans(zz[i,6:7]) average_value[i,5] - rowMeans(zz[i,8:9]) average_value[i,6] - rowMeans(zz[i,10:11]) #Sample B average_value[i,7] - rowMeans(zz[i,12:13]) average_value[i,8] - rowMeans(zz[i,14:15]) average_value[i,9] - rowMeans(zz[i,16:17]) average_value[i,10] - rowMeans(zz[i,18:19]) average_value[i,11] - rowMeans(zz[i,20:21]) #Sample C average_value[i,12] - rowMeans(zz[i,22:23]) average_value[i,13] - rowMeans(zz[i,24:25]) average_value[i,14] - rowMeans(zz[i,26:27]) average_value[i,15] - rowMeans(zz[i,28:29]) average_value[i,16] - rowMeans(zz[i,30:31]) #Sample D average_value[i,17] - rowMeans(zz[i,32:33]) average_value[i,18] - rowMeans(zz[i,34:35]) average_value[i,19] - rowMeans(zz[i,36:37]) average_value[i,20] - rowMeans(zz[i,38:39]) average_value[i,21] - rowMeans(zz[i,40:41]) } thanks __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Help with loops and how R stores data
On 02-Feb-08 21:16:41, R-novice wrote: I am trying to make an array c(3,8) that contains the averages of what is in another array c(9,8). I want to average rows 1:3, 4:6, 7:9 and have a loop replace the generic 1:24 values in my array with the average of the three rows. The problem I am having is that R only replaces the last value from the loops, and I am not experienced enough with R to know how it stores data when looping and how to overcome this problem. By having it print the avg, I was expecting to see 24 numbers, but it only gives me one. Here is my code. cts.sds-array(1:24,c(3,8)) for(i in 3){ for(j in 8){ avg-sum(exprdata[3*i-2:3*i,j]/3) cts.sds[i,j]-avg print(avg) } } print(cts.sds) Any help with this pesky matter will be greatly appreciated. I think you have made two types of mistake here. 1. You wrote for(i in 3) and for(i in 3). This means that 'i' will take only one value, namely 3; and 'j' will take only one value, namely 8. If you wanted to loop over i = 1,2,3 and j=1,2,3,4,5,6,7,8 then you should write for(i in (1:3)){ for(j in (1:8){ ... }} 2. This is more subtle, and you're far from the only person to have tripped over this one. Because of the order of precedence of the operators, in the epression 3*i-2:3*i for each value of 'i' it will first evaluate 2:3, namely {2,3}, and then evaluate the remainder. So, for say i=2, you will get two numbers 3*i-2*i = 2 and 3*i-3*i = 0, whereas what you presumably intended was (3*i-2):(3*i) = 4:6 = {4,5,6}. The way to avoid this trap is to use parantheses to force the order of evaluation you want: avg-sum(exprdata[(3*i-2):(3*i,j)]/3) Example: i-2 3*i-2:3*i # [1] 2 0 (3*i-2):(3*i) # [1] 4 5 6 The reason is that the : operator takes precedence over the binary operators *, + and -. Enter ?Syntax to get a listing of the various operators in order of precedence. Hoping this helps, Ted. E-Mail: (Ted Harding) [EMAIL PROTECTED] Fax-to-email: +44 (0)870 094 0861 Date: 04-Feb-08 Time: 08:18:05 -- XFMail -- __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Help with loops and how R stores data
I am trying to make an array c(3,8) that contains the averages of what is in another array c(9,8). I want to average rows 1:3, 4:6, 7:9 and have a loop replace the generic 1:24 values in my array with the average of the three rows. The problem I am having is that R only replaces the last value from the loops, and I am not experienced enough with R to know how it stores data when looping and how to overcome this problem. By having it print the avg, I was expecting to see 24 numbers, but it only gives me one. Here is my code. cts.sds-array(1:24,c(3,8)) for(i in 3){ for(j in 8){ avg-sum(exprdata[3*i-2:3*i,j]/3) cts.sds[i,j]-avg print(avg) } } print(cts.sds) Any help with this pesky matter will be greatly appreciated. -- View this message in context: http://www.nabble.com/Help-with-loops-and-how-R-stores-data-tp15247392p15247392.html Sent from the R help mailing list archive at Nabble.com. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.