[R] loop
I have to calculate a formula that gives me a ten components vector. I want to see how the components behave at varying the variable i. But when i run the following function: > bbayes<-c() > for(i in 1:100) { + xx<-t(X1_10)%*%X1_10 + xxmeno1<-solve(xx) + V<-xxmeno1*i + Vmeno1<-solve(V) + tx<-t(X1_10) + prpar<-solve(Vmeno1+xx) + snpar<-tx%*%y + bbayes<-prpar%*%snpar + } it oly gives me the vector calculated with the last value of the sequence, in this case 100. Could you please suggest how to print all the 100 vectors calculated for i in 1:100. Thank you in advance. Davide Crapis -- View this message in context: http://www.nabble.com/loop-tp19346683p19346683.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] loop
Hello all, I am trying to use m <- seq(-1,1,0.1) x1 <- vector() x2 <- vector() for(i in m){ x1[i] <- i x2[i] <- i^2 } dat <- data.frame(x1,x2) But, I have false result >dat x1 x2 1 1 1 could some tell me how it is possible to do this? Thank you! - [[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] Loop
Hello, I would like to build a list through the following codes."know1" & "know2" are some list obtained before. "know1" has the length of 50 (as for i), "know2" has the lengh of 50 (as for i), know1[[i]] has the length of 1000, know2[[i]] has the length of 1132. I would like to get the list "finalreturnc", for which finalreturnc[[i]][[j]] =know1[[i]]*know2[[i]][j]. But the loop does not seem to work, eg, I got the follwing value of finalreturnc ... [[50]][[1131]] NULL [[50]][[1132]] 1] -3.467047e-03 -2.963263e-02... finalreturnc <- list() volc1 <- list() for (i in 1:50){ for (j in 1:1132) { volc1[[j]] <- vector() volc1[[j]] <- know1[[i]]*know2[[i]][j] finalreturnc[[i]]<- list() finalreturnc[[i]][[j]]<- volc1[[j]] } } Could anyone give me some advice? Many thanks -- View this message in context: http://www.nabble.com/Loop-tf4712520.html#a13470236 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] Loop problem
Dear all, I want to write ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) state ment in a loop . How can I write it ? > pk [,1] [,2] [,3] [1,] -1.1354816 0.9808877 -0.9446314 [2,] 0.7787378 0.4536944 0.3204882 [3,] -1.7274907 1.5112011 1.4481839 [4,] 1.0629145 0.5976109 -0.5277638 > pk<-matrix(rnorm(12),nrow=4,ncol=3) > pk [,1] [,2] [,3] [1,] -1.1354816 0.9808877 -0.9446314 [2,] 0.7787378 0.4536944 0.3204882 [3,] -1.7274907 1.5112011 1.4481839 [4,] 1.0629145 0.5976109 -0.5277638 > ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) > ck [,1] [,2] [,3] [1,] -1.135482 0.9808877 -0.9446314 [2,] -1.135482 0.9808877 -0.9446314 [3,] -1.135482 0.9808877 -0.9446314 [4,] -1.135482 0.9808877 -0.9446314 Thanks for your help Fernanda Lopez Netherlands [[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] loop
I would suggest that you use a 'list' since it seems that the result is more than a single value: bbayes<-list() for(i in 1:100) { xx<-t(X1_10)%*%X1_10 xxmeno1<-solve(xx) V<-xxmeno1*i Vmeno1<-solve(V) tx<-t(X1_10) prpar<-solve(Vmeno1+xx) snpar<-tx%*%y bbayes[[i]]<-prpar%*%snpar } On Sat, Sep 6, 2008 at 9:29 AM, Davide Crapis <[EMAIL PROTECTED]> wrote: > > I have to calculate a formula that gives me a ten components vector. I want > to see how the components behave at varying the variable i. > But when i run the following function: >> bbayes<-c() >> for(i in 1:100) { > + xx<-t(X1_10)%*%X1_10 > + xxmeno1<-solve(xx) > + V<-xxmeno1*i > + Vmeno1<-solve(V) > + tx<-t(X1_10) > + prpar<-solve(Vmeno1+xx) > + snpar<-tx%*%y > + bbayes<-prpar%*%snpar > + } > > it oly gives me the vector calculated with the last value of the sequence, > in this case 100. > Could you please suggest how to print all the 100 vectors calculated for i > in 1:100. > > Thank you in advance. > > Davide Crapis > -- > View this message in context: > http://www.nabble.com/loop-tp19346683p19346683.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. > -- Jim Holtman Cincinnati, OH +1 513 646 9390 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.
Re: [R] loop
It's exactely what I was looking for. Thanks a lot -- View this message in context: http://www.nabble.com/loop-tp19346683p19356409.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] R loop
I all I am just trying to get the idea of a loop if statement for another purpose. I was going to label a new variable based on date ie first week 1, second week 2 etc. My code in bold is wrong but seems logical to me, could someone help. x <- rep(c(2660156,2663703,2658165,2659303,2661531,2660914),c(2,2,2,2,1,1)) y <- rep(c(6476767,6475013,6475487,6479659,6477004,6476388),c(2,2,2,2,1,1)) date <- rep(as.Date(c("2008-01-01","2008-01-14","2008-01-28"), format = "%Y-%m-%d"),c(4,4,2)) a<-data.frame(x,y,date) a$wk<-rep(c(0),nrow(a)) a set<-as.Date(c("2008-01-01"), format = "%Y-%m-%d") set for(i in a$date){ if (a$date[i]>set & a$date[i]set +7){a$wk<-2}else {a$wk<-3} } a Kind regards andy Andrew McFadden MVS BVSc Incursion Investigator Investigation & Diagnostic Centres - Wallaceville Biosecurity New Zealand Ministry of Agriculture and Forestry Phone 04 894 5600 Fax 04 894 4973 Mobile 029 894 5611 Postal address: Investigation and Diagnostic Centre- Wallaceville Box 40742 Ward St Upper Hutt This email message and any attachment(s) is intended solely for the addressee(s) named above. The information it contains is confidential and may be legally privileged. Unauthorised use of the message, or the information it contains, may be unlawful. If you have received this message by mistake please call the sender immediately on 64 4 8940100 or notify us by return email and erase the original message and attachments. Thank you. The Ministry of Agriculture and Forestry accepts no responsibility for changes made to this email or to any attachments after transmission from the office. [[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] loop
> Date: Wed, 05 Mar 2008 15:59:59 +0100 (CET) > From: Neuer Arkadasch <[EMAIL PROTECTED]> > Sender: [EMAIL PROTECTED] > Precedence: list > > Hello all, > > I am trying to use > > m <- seq(-1,1,0.1) > x1 <- vector() > x2 <- vector() > for(i in m){ > x1[i] <- i > x2[i] <- i^2 > } > dat <- data.frame(x1,x2) > But, I have false result > >dat > x1 x2 > 1 1 1 > It does not seem to be false: I am getting the same result. You should probably explain what you expected and what you are trying to achieve. Giovanni > could some tell me how it is possible to do this? > > Thank you! > > > > > - > > [[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. > > -- Giovanni Petris <[EMAIL PROTECTED]> Associate Professor Department of Mathematical Sciences University of Arkansas - Fayetteville, AR 72701 Ph: (479) 575-6324, 575-8630 (fax) http://definetti.uark.edu/~gpetris/ __ 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] loop
Try this: m <- seq(-1,1,0.1) x1 <- vector(length=length(m)) x2 <- vector(length=length(m)) for(i in m){ x1[i] <- i x2[i] <- i^2 } dat <- data.frame(x1,x2) Ravi. --- Ravi Varadhan, Ph.D. Assistant Professor, The Center on Aging and Health Division of Geriatric Medicine and Gerontology Johns Hopkins University Ph: (410) 502-2619 Fax: (410) 614-9625 Email: [EMAIL PROTECTED] Webpage: http://www.jhsph.edu/agingandhealth/People/Faculty/Varadhan.html -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Neuer Arkadasch Sent: Wednesday, March 05, 2008 10:00 AM To: [EMAIL PROTECTED] Subject: [R] loop Hello all, I am trying to use m <- seq(-1,1,0.1) x1 <- vector() x2 <- vector() for(i in m){ x1[i] <- i x2[i] <- i^2 } dat <- data.frame(x1,x2) But, I have false result >dat x1 x2 1 1 1 could some tell me how it is possible to do this? Thank you! - [[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] loop
m <- seq(-1,1,0.1) x1 <- c() x2 <- c() for(i in 1:length(m)){ x1[i] <- m[i] x2[i] <- m[i]^2 } dat <- data.frame(x1,x2) -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Neuer Arkadasch Sent: March 5, 2008 10:00 AM To: [EMAIL PROTECTED] Subject: [R] loop Hello all, I am trying to use m <- seq(-1,1,0.1) x1 <- vector() x2 <- vector() for(i in m){ x1[i] <- i x2[i] <- i^2 } dat <- data.frame(x1,x2) But, I have false result >dat x1 x2 1 1 1 could some tell me how it is possible to do this? Thank you! - [[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] loop
Why not simply? m <- seq(-1, 1, by = 0.1) dat <- data.frame(m, m^2) - Erik Iverson Neuer Arkadasch wrote: > Hello all, > > I am trying to use > > m <- seq(-1,1,0.1) > x1 <- vector() > x2 <- vector() > for(i in m){ > x1[i] <- i > x2[i] <- i^2 > } > dat <- data.frame(x1,x2) > But, I have false result > >dat > x1 x2 > 1 1 1 > > could some tell me how it is possible to do this? > > Thank you! > > > > > - > > [[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] loop
Thank you Yinghai, that's what I need :-)! Yinghai Deng <[EMAIL PROTECTED]> schrieb: m <- seq(-1,1,0.1) x1 <- c() x2 <- c() for(i in 1:length(m)){ x1[i] <- m[i] x2[i] <- m[i]^2 } dat <- data.frame(x1,x2) -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Neuer Arkadasch Sent: March 5, 2008 10:00 AM To: [EMAIL PROTECTED] Subject: [R] loop Hello all, I am trying to use m <- seq(-1,1,0.1) x1 <- vector() x2 <- vector() for(i in m){ x1[i] <- i x2[i] <- i^2 } dat <- data.frame(x1,x2) But, I have false result >dat x1 x2 1 1 1 could some tell me how it is possible to do this? Thank you! - [[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. - Lesen Sie Ihre E-Mails jetzt einfach von unterwegs.. [[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] loop
m <- seq(-1,1,0.1) x1 <- vector() x2 <- vector() # the loop statement was incorrect. for(i in 1:length(m)){ x1[i] <- m[i] x2[i] <- m[i]^2 } dat <- data.frame(x1,x2) # But why not something like this? There is no need for a loop. x1 <- seq(-1,1,0.1) mdat <- data.frame(x1, x2=x1^2) --- Neuer Arkadasch <[EMAIL PROTECTED]> wrote: > Hello all, > > I am trying to use > > m <- seq(-1,1,0.1) > x1 <- vector() > x2 <- vector() > for(i in m){ > x1[i] <- i > x2[i] <- i^2 > } > dat <- data.frame(x1,x2) > But, I have false result > >dat > x1 x2 > 1 1 1 > > could some tell me how it is possible to do this? > > Thank you! > > > > > - > > [[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] loop
Hi [EMAIL PROTECTED] napsal dne 05.03.2008 18:04:35: > Thank you Yinghai, that's what I need :-)! > > Yinghai Deng <[EMAIL PROTECTED]> schrieb: m <- seq(-1,1,0.1) > x1 <- c() > x2 <- c() > for(i in 1:length(m)){ > x1[i] <- m[i] > x2[i] <- m[i]^2 > } > dat <- data.frame(x1,x2) The same result you will get by dat2<-data.frame(x1=m, x2=m^2) > all.equal(dat,dat2) [1] TRUE Regards Petr > > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] Behalf Of Neuer Arkadasch > Sent: March 5, 2008 10:00 AM > To: [EMAIL PROTECTED] > Subject: [R] loop > > > Hello all, > > I am trying to use > > m <- seq(-1,1,0.1) > x1 <- vector() > x2 <- vector() > for(i in m){ > x1[i] <- i > x2[i] <- i^2 > } > dat <- data.frame(x1,x2) > But, I have false result > >dat > x1 x2 > 1 1 1 > > could some tell me how it is possible to do this? > > Thank you! > > > > > - > > [[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. > > > > > - > Lesen Sie Ihre E-Mails jetzt einfach von unterwegs.. >[[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.
[R] Loop problem
Dear all, I have a problem with a loop, if anyone has any knowledge on these things I would appreciate some comments. The code below is designed to allow me to extract the top record of the data frame, and them remove rows from the data frame which have an index close to the extracted top record. topstorm<-subset(rankeddataset[1,]) ## Extracts the top storm topstormindex<-rankeddataset[1,1] ## Finds the top storm start index startindex<-topstormindex-48 ## sets the start and end indexes endindex<-topstorminde+48 rankeddataset<-rankeddataset[-1,] ## Creates a new list with the top storm removed ##This section of code needs looped. It removes storms from the list which are too close to the extracted storm for (i in 1:30){ if (rankeddataset[i,1]>startindex && rankeddataset[i,1]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] loop function
Hi, If I have this values: 21 23 14 58 26 How can I sum the values by a progression like this: (21) (21 + 23) (21 + 23 + 14) (21 + 23 + 14 + 58) (21 + 23 + 14 + 58 + 26) (21 + 23 + 14 + 58 + 26) I've try with the function "loop" Best Wishes, Alfredo [[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] loop problem
Dear R members I have a problem regarding storing the lists. Let L=number of distinct values of any predictor (say L=5) P=number of predictors (say P=20) g1 <- c() for(i in 1:P){ if(L > 1){ for(j in 1:(L-1)){ g <- g1[j] <- g } } g2[]=sort.list(g1) } Now the question is: What should we use inside brackets of g2[], whether "i" or some thing else? If L is not greater than 1 then there will be a "NULL" for g2. We don't want to store it in g2, so how can we handle this problem. Looking forward for some help. Thanks and best regards Muhammad Azam [[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] Loop question
Hi everyone, I am trying to accomplish a small task that is giving me quite a headache. I would like to automatically generate a series of matrices and give them successive names. Here is what I thought at first: t1<-matrix(0, nrow=250, ncol=1) for(i in 1:10){ t1[i]<-rnorm(250) } What I intended was that the loop would create 10 different matrices with a single column of 250 values randomly selected from a normal distribution, and that they would be labeled t11, t12, t13, t14 etc. Can anyone steer me in the right direction with this one? Thanks! Brendan __ 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] loop help
Hi all, I'm stuck trying to get syntax correct for the follwing type of loop. I would like to find the column with the largest value in a given row, and create a new column with a categorical variable indicating which column the highest value of "i" comes from. too=data.frame(A=rnorm(10,1),B=rnorm(10,2),C=rnorm(10,1.5)) too$large=0 too$large=for (i in 1:length(too[,c(1,2,3)])) { if (too$A[i] > too$B[i] & too$C[i]) {too$large[i]=1} else if (too$B[i] > too$A[i] & too$C[i]) {too$large[i]=2} else if (too$C[i] > too$A[i] & too$B[i]) {too$large[i]=3}} Ultiamtely this is not working for me, any hints would be much appreciated! -- David Depew PhD Candidate Department of Biology University of Waterloo 200 University Ave W Waterloo, Ontario, Canada N2L 3G1 T:(1)-519-888-4567 x 33895 F:(1)-519-746-0614 dde...@scimail.uwaterloo.ca http://www.science.uwaterloo.ca/~ddepew __ 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] loop with files
I'm trying to make a loop with many files... > library(dplR) > > files <- system("ls *.rwl", intern=TRUE) > > files [1] "cimfasy.rwl" "rocquce.rwl" > for (i in files) {a <- read.rwl(i,header=0)} There are 70 series There are 21 series > class(a) [1] "data.frame" This loop import all the files rwl in a single data.frame ( a ). Can I import a single files to a single data.frame? like this: for (i in files) {cimfasy <- read.rwl(i,header=0)} for (i in files) {rocquce <- read.rwl(i,header=0)} Thanks in advance, Alfredo __ 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] loop calculation
something like: ## set PIJ to be negative while (any(PIJ<0)) { ## calculate PIJ } __ 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] Loop problem
try this: pk <- matrix(rnorm(12), 4, 3) matrix(rep(pk[1, ], each = 4), 4) I hope it helps. Best, Dimitris Dimitris Rizopoulos Biostatistical Centre School of Public Health Catholic University of Leuven Address: Kapucijnenvoer 35, Leuven, Belgium Tel: +32/(0)16/336899 Fax: +32/(0)16/337015 Web: http://med.kuleuven.be/biostat/ http://www.student.kuleuven.be/~m0390867/dimitris.htm - Original Message - From: "fernanda lopez" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> Sent: Monday, July 14, 2008 10:33 AM Subject: [R] Loop problem Dear all, I want to write ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) state ment in a loop . How can I write it ? pk [,1] [,2] [,3] [1,] -1.1354816 0.9808877 -0.9446314 [2,] 0.7787378 0.4536944 0.3204882 [3,] -1.7274907 1.5112011 1.4481839 [4,] 1.0629145 0.5976109 -0.5277638 pk<-matrix(rnorm(12),nrow=4,ncol=3) pk [,1] [,2] [,3] [1,] -1.1354816 0.9808877 -0.9446314 [2,] 0.7787378 0.4536944 0.3204882 [3,] -1.7274907 1.5112011 1.4481839 [4,] 1.0629145 0.5976109 -0.5277638 ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) ck [,1] [,2] [,3] [1,] -1.135482 0.9808877 -0.9446314 [2,] -1.135482 0.9808877 -0.9446314 [3,] -1.135482 0.9808877 -0.9446314 [4,] -1.135482 0.9808877 -0.9446314 Thanks for your help Fernanda Lopez Netherlands [[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. Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm __ 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] Loop problem
Hi, do you mean this? pk<-matrix(rnorm(12),nrow=4,ncol=3) ck1<-cbind(rep(pk[,1],4),rep(pk[,2],4),rep(pk[,3],4)) ## or ck2<-cbind(rep(pk[,1],each=4),rep(pk[,2],each=4),rep(pk[,3],each=4)) pk ck1 ck2 best, Daniel fernanda lopez wrote: > > Dear all, > I want to > write ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) state > ment > in a loop . How can I write it ? > > > > > >> pk >[,1] [,2] [,3] > [1,] -1.1354816 0.9808877 -0.9446314 > [2,] 0.7787378 0.4536944 0.3204882 > [3,] -1.7274907 1.5112011 1.4481839 > [4,] 1.0629145 0.5976109 -0.5277638 > > > >> pk<-matrix(rnorm(12),nrow=4,ncol=3) >> pk >[,1] [,2] [,3] > [1,] -1.1354816 0.9808877 -0.9446314 > [2,] 0.7787378 0.4536944 0.3204882 > [3,] -1.7274907 1.5112011 1.4481839 > [4,] 1.0629145 0.5976109 -0.5277638 > >> ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) >> ck > [,1] [,2] [,3] > [1,] -1.135482 0.9808877 -0.9446314 > [2,] -1.135482 0.9808877 -0.9446314 > [3,] -1.135482 0.9808877 -0.9446314 > [4,] -1.135482 0.9808877 -0.9446314 > > > Thanks for your help > > Fernanda Lopez > Netherlands > > [[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. > > -- View this message in context: http://www.nabble.com/Loop-problem-tp18439649p18439918.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] Loop problem
Try this: pk[rep(1, 4), ] On Mon, Jul 14, 2008 at 4:33 AM, fernanda lopez <[EMAIL PROTECTED]> wrote: > Dear all, > I want to > write ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) state ment > in a loop . How can I write it ? > > > > > >> pk > [,1] [,2] [,3] > [1,] -1.1354816 0.9808877 -0.9446314 > [2,] 0.7787378 0.4536944 0.3204882 > [3,] -1.7274907 1.5112011 1.4481839 > [4,] 1.0629145 0.5976109 -0.5277638 > > > >> pk<-matrix(rnorm(12),nrow=4,ncol=3) >> pk > [,1] [,2] [,3] > [1,] -1.1354816 0.9808877 -0.9446314 > [2,] 0.7787378 0.4536944 0.3204882 > [3,] -1.7274907 1.5112011 1.4481839 > [4,] 1.0629145 0.5976109 -0.5277638 > >> ck<-cbind(rep(pk[1,1],4),rep(pk[1,2],4),rep(pk[1,3],4)) >> ck > [,1] [,2] [,3] > [1,] -1.135482 0.9808877 -0.9446314 > [2,] -1.135482 0.9808877 -0.9446314 > [3,] -1.135482 0.9808877 -0.9446314 > [4,] -1.135482 0.9808877 -0.9446314 > > > Thanks for your help > > Fernanda Lopez > Netherlands > >[[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.
[R] loop with dates
Hello, I am trying to do a loop with dates, but when I try to use the index is not a date. Fcorte <- as.Date('2008/11/30',format = "%Y/%m/%d") fini <- Fcorte + 1 ffin <- seq(fini,by='months',length=2)[2] - 1 for (i in seq(fini,to = ffin, by='days')) print (weekdays(i)) # i doesn't a date How can I do a loop with dates and get the index of each date? are there a method to convert the index i to date? Thanks in advance. [[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 loop
The bolding is lost in plain-text email, but some things to note: :: for(i in a$date){ - this will make i take on date values, you probably meant i to index the rows of a[] :: you missed indexing in your replacements in the then and else clauses :: you probably want some equalities in your test conditions, not all '<' '>' inequalities :: need an extra condition for the 2 weeks test clause for(i in seq(nrow(a))){ if (a$date[i]>=set & a$date[i]=set +7 & a$date[i] a x y date wk 1 2660156 6476767 2008-01-01 1 2 2660156 6476767 2008-01-01 1 3 2663703 6475013 2008-01-01 1 4 2663703 6475013 2008-01-01 1 5 2658165 6475487 2008-01-14 2 6 2658165 6475487 2008-01-14 2 7 2659303 6479659 2008-01-14 2 8 2659303 6479659 2008-01-14 2 9 2661531 6477004 2008-01-28 3 10 2660914 6476388 2008-01-28 3 -Original Message- From: [EMAIL PROTECTED] on behalf of Andrew McFadden Sent: Thu 6/5/2008 8:46 PM To: r-help@r-project.org Subject: [R] R loop I all I am just trying to get the idea of a loop if statement for another purpose. I was going to label a new variable based on date ie first week 1, second week 2 etc. My code in bold is wrong but seems logical to me, could someone help. x <- rep(c(2660156,2663703,2658165,2659303,2661531,2660914),c(2,2,2,2,1,1)) y <- rep(c(6476767,6475013,6475487,6479659,6477004,6476388),c(2,2,2,2,1,1)) date <- rep(as.Date(c("2008-01-01","2008-01-14","2008-01-28"), format = "%Y-%m-%d"),c(4,4,2)) a<-data.frame(x,y,date) a$wk<-rep(c(0),nrow(a)) a set<-as.Date(c("2008-01-01"), format = "%Y-%m-%d") set for(i in a$date){ if (a$date[i]>set & a$date[i]set +7){a$wk<-2}else {a$wk<-3} } a Kind regards andy Andrew McFadden MVS BVSc Incursion Investigator Investigation & Diagnostic Centres - Wallaceville Biosecurity New Zealand Ministry of Agriculture and Forestry Phone 04 894 5600 Fax 04 894 4973 Mobile 029 894 5611 Postal address: Investigation and Diagnostic Centre- Wallaceville Box 40742 Ward St Upper Hutt This email message and any attachment(s) is intended solely for the addressee(s) named above. The information it contains is confidential and may be legally privileged. Unauthorised use of the message, or the information it contains, may be unlawful. If you have received this message by mistake please call the sender immediately on 64 4 8940100 or notify us by return email and erase the original message and attachments. Thank you. The Ministry of Agriculture and Forestry accepts no responsibility for changes made to this email or to any attachments after transmission from the office. [[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] R loop
But note that you could do this in a vectorized fashion and not use a loop at all: > a$wk <- (as.numeric((a$date - set)) %/% 7) + 1 > a x y date wk 1 2660156 6476767 2008-01-01 1 2 2660156 6476767 2008-01-01 1 3 2663703 6475013 2008-01-01 1 4 2663703 6475013 2008-01-01 1 5 2658165 6475487 2008-01-14 2 6 2658165 6475487 2008-01-14 2 7 2659303 6479659 2008-01-14 2 8 2659303 6479659 2008-01-14 2 9 2661531 6477004 2008-01-28 4 10 2660914 6476388 2008-01-28 4 > -Original Message- From: [EMAIL PROTECTED] on behalf of Steven McKinney Sent: Thu 6/5/2008 9:01 PM To: Andrew McFadden; r-help@r-project.org Subject: Re: [R] R loop The bolding is lost in plain-text email, but some things to note: :: for(i in a$date){ - this will make i take on date values, you probably meant i to index the rows of a[] :: you missed indexing in your replacements in the then and else clauses :: you probably want some equalities in your test conditions, not all '<' '>' inequalities :: need an extra condition for the 2 weeks test clause for(i in seq(nrow(a))){ if (a$date[i]>=set & a$date[i]=set +7 & a$date[i] a x y date wk 1 2660156 6476767 2008-01-01 1 2 2660156 6476767 2008-01-01 1 3 2663703 6475013 2008-01-01 1 4 2663703 6475013 2008-01-01 1 5 2658165 6475487 2008-01-14 2 6 2658165 6475487 2008-01-14 2 7 2659303 6479659 2008-01-14 2 8 2659303 6479659 2008-01-14 2 9 2661531 6477004 2008-01-28 3 10 2660914 6476388 2008-01-28 3 -Original Message- From: [EMAIL PROTECTED] on behalf of Andrew McFadden Sent: Thu 6/5/2008 8:46 PM To: r-help@r-project.org Subject: [R] R loop I all I am just trying to get the idea of a loop if statement for another purpose. I was going to label a new variable based on date ie first week 1, second week 2 etc. My code in bold is wrong but seems logical to me, could someone help. x <- rep(c(2660156,2663703,2658165,2659303,2661531,2660914),c(2,2,2,2,1,1)) y <- rep(c(6476767,6475013,6475487,6479659,6477004,6476388),c(2,2,2,2,1,1)) date <- rep(as.Date(c("2008-01-01","2008-01-14","2008-01-28"), format = "%Y-%m-%d"),c(4,4,2)) a<-data.frame(x,y,date) a$wk<-rep(c(0),nrow(a)) a set<-as.Date(c("2008-01-01"), format = "%Y-%m-%d") set for(i in a$date){ if (a$date[i]>set & a$date[i]set +7){a$wk<-2}else {a$wk<-3} } a Kind regards andy Andrew McFadden MVS BVSc Incursion Investigator Investigation & Diagnostic Centres - Wallaceville Biosecurity New Zealand Ministry of Agriculture and Forestry Phone 04 894 5600 Fax 04 894 4973 Mobile 029 894 5611 Postal address: Investigation and Diagnostic Centre- Wallaceville Box 40742 Ward St Upper Hutt This email message and any attachment(s) is intended solely for the addressee(s) named above. The information it contains is confidential and may be legally privileged. Unauthorised use of the message, or the information it contains, may be unlawful. If you have received this message by mistake please call the sender immediately on 64 4 8940100 or notify us by return email and erase the original message and attachments. Thank you. The Ministry of Agriculture and Forestry accepts no responsibility for changes made to this email or to any attachments after transmission from the office. [[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. __ 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 loop
Hi Andy, I see two problems: First of all, it must be a$wk[i] <- 1 and not a$wk <- 1, since this way it makes all 10 entries of a$wk to be 1. But R won't complain about this! What R should complain about is your loop. If you write for (i in a$date) it means that i loops between all the VALUES in a$date, not their indexes (i.e. i will be "2008-01-01" 4 times, "2008-01-14" 4 times, etc). So replace your loop by for (i in 1:length(a$date)) or alternatively your condition should be if (i > set) and not if (a$date[i] > set) since a$date[as.Date("2008-01-01")] doesn't make much sense. But if you do this you will have problem changing the appropriate value of a$wk. --- On Fri, 6/6/08, Andrew McFadden <[EMAIL PROTECTED]> wrote: > From: Andrew McFadden <[EMAIL PROTECTED]> > Subject: [R] R loop > To: r-help@r-project.org > Received: Friday, 6 June, 2008, 1:46 PM > I all > > I am just trying to get the idea of a loop if statement for > another > purpose. I was going to label a new variable based on date > ie first week > 1, second week 2 etc. My code in bold is wrong but seems > logical to me, > could someone help. > > x <- > rep(c(2660156,2663703,2658165,2659303,2661531,2660914),c(2,2,2,2,1,1)) > y <- > rep(c(6476767,6475013,6475487,6479659,6477004,6476388),c(2,2,2,2,1,1)) > date <- > rep(as.Date(c("2008-01-01","2008-01-14","2008-01-28"), > format > = "%Y-%m-%d"),c(4,4,2)) > a<-data.frame(x,y,date) > a$wk<-rep(c(0),nrow(a)) > a > set<-as.Date(c("2008-01-01"), format = > "%Y-%m-%d") > set > > for(i in a$date){ > if (a$date[i]>set & a$date[i] ){a$wk<-1}else > if (a$date[i]>set +7){a$wk<-2}else {a$wk<-3} > } > a > > Kind regards > > andy > > Andrew McFadden MVS BVSc > Incursion Investigator > Investigation & Diagnostic Centres - Wallaceville > Biosecurity New > Zealand Ministry of Agriculture and Forestry > > Phone 04 894 5600 Fax 04 894 4973 Mobile 029 894 5611 > Postal address: > Investigation and Diagnostic Centre- Wallaceville Box 40742 > Ward St > Upper Hutt > > > > This email message and any attachment(s) is intended solely > for the > addressee(s) named above. The information it contains is > confidential > and may be legally privileged. Unauthorised use of the > message, or the > information it contains, may be unlawful. If you have > received this > message by mistake please call the sender immediately on 64 > 4 8940100 > or notify us by return email and erase the original message > and > attachments. Thank you. > > The Ministry of Agriculture and Forestry accepts no > responsibility for > changes made to this email or to any attachments after > transmission from > the office. > > > [[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] R loop
Note that "%Y-%m-%d" is the default format so you can omit it. Perhaps you want something along these lines (modify formula to get the precise numbering you like): a$wk <- julian(a$date, as.Date("2008-01-01")) %/% 7 Also note %W can be used as a format string. See ?strptime for the codes. R News 4/1 has an article about dates. On Thu, Jun 5, 2008 at 11:46 PM, Andrew McFadden <[EMAIL PROTECTED]> wrote: > I all > > I am just trying to get the idea of a loop if statement for another > purpose. I was going to label a new variable based on date ie first week > 1, second week 2 etc. My code in bold is wrong but seems logical to me, > could someone help. > > x <- > rep(c(2660156,2663703,2658165,2659303,2661531,2660914),c(2,2,2,2,1,1)) > y <- > rep(c(6476767,6475013,6475487,6479659,6477004,6476388),c(2,2,2,2,1,1)) > date <- rep(as.Date(c("2008-01-01","2008-01-14","2008-01-28"), format > = "%Y-%m-%d"),c(4,4,2)) > a<-data.frame(x,y,date) > a$wk<-rep(c(0),nrow(a)) > a > set<-as.Date(c("2008-01-01"), format = "%Y-%m-%d") > set > > for(i in a$date){ > if (a$date[i]>set & a$date[i] if (a$date[i]>set +7){a$wk<-2}else {a$wk<-3} > } > a > > Kind regards > > andy > > Andrew McFadden MVS BVSc > Incursion Investigator > Investigation & Diagnostic Centres - Wallaceville Biosecurity New > Zealand Ministry of Agriculture and Forestry > > Phone 04 894 5600 Fax 04 894 4973 Mobile 029 894 5611 Postal address: > Investigation and Diagnostic Centre- Wallaceville Box 40742 Ward St > Upper Hutt > > > > This email message and any attachment(s) is intended solely for the > addressee(s) named above. The information it contains is confidential > and may be legally privileged. Unauthorised use of the message, or the > information it contains, may be unlawful. If you have received this > message by mistake please call the sender immediately on 64 4 8940100 > or notify us by return email and erase the original message and > attachments. Thank you. > > The Ministry of Agriculture and Forestry accepts no responsibility for > changes made to this email or to any attachments after transmission from > the office. > > >[[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] Loop problem
Basically you are moving the data up and then incrementing to the next row. Here is an example; assume that you are at the 2nd entry: 1 2 <== here 3 4 Now your loop index is 2 and you remove the current data ('2') and are left with: 1 3 <== index of 2 points here 4 Now you increment the index to 3 and you get 1 3 4 <== now here So you have skipped 3. What you should be doing is determining all the index values that meet your criteria and then deleting them all at once, or start from the bottom of the dataframe and work up. On 3/26/08, Jamie Ledingham <[EMAIL PROTECTED]> wrote: > Dear all, I have a problem with a loop, if anyone has any knowledge on > these things I would appreciate some comments. The code below is > designed to allow me to extract the top record of the data frame, and > them remove rows from the data frame which have an index close to the > extracted top record. > > > topstorm<-subset(rankeddataset[1,]) ## Extracts the top storm > topstormindex<-rankeddataset[1,1] ## Finds the top storm start index > startindex<-topstormindex-48 ## sets the start and end indexes > endindex<-topstorminde+48 > rankeddataset<-rankeddataset[-1,] ## Creates a new list with the top > storm removed > > ##This section of code needs looped. It removes storms from the list > which are too close to the extracted storm > > for (i in 1:30){ > if (rankeddataset[i,1]>startindex && rankeddataset[i,1] {rankeddataset<-rankeddataset[-i,]} > } > > Here is some example data: > > 82856 15 / 6 / 1966 82856:8287925.9 > 82857 15 / 6 / 1966 82857:8288020.5 > 83036 23 / 6 / 1966 83036:8305917.3 > 87250 15 / 12 / 1966 87250:8727315.9 > > The loop does not currently work, it seems to remove every second line > or so. Can anyone suggest why this might be, I'm not particularly > experienced in using loops so it may be a rookie mistake. Thanks in > advance. > Jamie Ledingham > > __ > 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 Cincinnati, OH +1 513 646 9390 What is the problem 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.
Re: [R] Loop problem
Jamie Ledingham wrote: > Dear all, I have a problem with a loop, if anyone has any knowledge on > these things I would appreciate some comments. The code below is > designed to allow me to extract the top record of the data frame, and > them remove rows from the data frame which have an index close to the > extracted top record. > > > topstorm<-subset(rankeddataset[1,]) ## Extracts the top storm > topstormindex<-rankeddataset[1,1] ## Finds the top storm start index > startindex<-topstormindex-48 ## sets the start and end indexes > endindex<-topstorminde+48 > rankeddataset<-rankeddataset[-1,] ## Creates a new list with the top > storm removed > > ##This section of code needs looped. It removes storms from the list > which are too close to the extracted storm > > for (i in 1:30){ > if (rankeddataset[i,1]>startindex && rankeddataset[i,1] {rankeddataset<-rankeddataset[-i,]} > } > > Here is some example data: > >82856 15 / 6 / 1966 82856:8287925.9 >82857 15 / 6 / 1966 82857:8288020.5 >83036 23 / 6 / 1966 83036:8305917.3 >87250 15 / 12 / 1966 87250:8727315.9 > Hi again Jamie, I had a bit of time tonight and recognized your problem. I think the following function will do what you want, although it is probably not the most elegant solution. I would check it manually with a small data file and a small "howmany" argument to make sure that it is picking up the maxima you want. find.max.rain<-function(raindata,howmany) { # a lazy way of getting the same structure as raindata # it assumes that raindata has the data structure that you want maxrain<-raindata[1:howmany,] for(i in 1:howmany) { # get the current number of rows nrows<-dim(raindata)[1] # find the first maximum value thismax<-which.max(raindata$cumrain) # transfer it to the return data frame maxrain[i,]<-raindata[thismax,] # calculate the minimum index for the 48 hour gap mindex<-thismax-48 # make sure it is at least 1 if(mindex < 1) mindex <- 1 # calculate the maximum index for the gap maxdex<-thismax+48 # make sure it doesn't go past the end of the data frame if(maxdex > nrows) maxdex<-nrows # chop out that time period raindata<-raindata[-(mindex:maxdex),] } return(maxrain) } Jim __ 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] Loop problem
Oops, missed the first line of the example: storm.data<-data.frame(meas.index=10001:2,cumrain=runif(1,-10,10)+10) You can generalize the function to whatever column names you have like this: find.max.rain<-function(raindata,howmany,raincol) { # a lazy way of getting the same structure as raindata # it assumes that raindata has the data structure that you want maxrain<-raindata[1:howmany,] for(i in 1:howmany) { raindim<-dim(raindata) thismax<-which.max(raindata[[raincol]]) cat(thismax," ") maxrain[i,]<-raindata[thismax,] mindex<-thismax-48 if(mindex < 1) mindex <- 1 maxdex<-thismax+48 cat(mindex,maxdex," ") if(maxdex > raindim[1]) maxdex<-raindim[1] raindata<-raindata[-(mindex:maxdex),] cat(raindim[1]," ") } cat("\n") return(maxrain) } find.max.rain(storm.data,50,"cumrain") Jim __ 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] loop function
Is this what you want: > x [1] 21 23 14 58 26 > cumsum(x) [1] 21 44 58 116 142 On 9/13/07, Alfredo Alessandrini <[EMAIL PROTECTED]> wrote: > Hi, > > If I have this values: > > 21 > 23 > 14 > 58 > 26 > > > How can I sum the values by a progression like this: > > (21) > (21 + 23) > (21 + 23 + 14) > (21 + 23 + 14 + 58) > (21 + 23 + 14 + 58 + 26) > (21 + 23 + 14 + 58 + 26) > > I've try with the function "loop" > > Best Wishes, > > Alfredo > >[[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 Cincinnati, OH +1 513 646 9390 What is the problem 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.
Re: [R] loop function
Alfredo Alessandrini wrote: > Hi, > > If I have this values: > > 21 > 23 > 14 > 58 > 26 > > > How can I sum the values by a progression like this: > > (21) > (21 + 23) > (21 + 23 + 14) > (21 + 23 + 14 + 58) > (21 + 23 + 14 + 58 + 26) > (21 + 23 + 14 + 58 + 26) > > I've try with the function "loop" > > Try cumsum() instead... > Best Wishes, > > Alfredo > > [[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. > -- O__ Peter Dalgaard Øster Farimagsgade 5, Entr.B c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~ - ([EMAIL PROTECTED]) FAX: (+45) 35327907 __ 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] Loop on characters
Hi, suppose I have three vectors like : l1 = 1:4 l2 = 4:9 l3 = 16:67 now I want to construct a loop like : for (i in 1:3) { count1[i] = length(li) # i.e. it will take l1, l2, l3 according to value of i } Can anyone please tell me how to do that? Regards, -- View this message in context: http://www.nabble.com/Loop-on-characters-tp21949173p21949173.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] loop problem
Muhammad Azam wrote: Dear R members I have a problem regarding storing the lists. Let L=number of distinct values of any predictor (say L=5) P=number of predictors (say P=20) g1 <- c() for(i in 1:P){ if(L > 1){ for(j in 1:(L-1)){ g <- g1[j] <- g } } g2[]=sort.list(g1) } Now the question is: What should we use inside brackets of g2[], whether "i" or some thing else? If L is not greater than 1 then there will be a "NULL" for g2. We don't want to store it in g2, so how can we handle this problem. Looking forward for some help. Thanks and Hi Muhammad, The first thing I would ask is "Why not store NULL in g2[[i]] if that element is NULL?". If you do this: for(i in 1:P) { if(L > 1) { g1<-rep(NA,L) for(j in 1:(L-1)) g1[j]<-... g2[[i]]<-sort.list(g1) } } you will have fewer elements in g2 than you have sets of predictors and will then have to match up the sets of predictors with the elements in g2. I think you could just test for NULL is.null(g2[[i]]) later on if you don't want to process these in a subsequent step. Jim __ 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] Loop question
Dear Brendan, One way could be either bigt <- sapply(1:10,function(x) rnorm(250)) colnames(bigt) <- paste('t',1:10,sep="") bigt or bigt2 <- NULL for(i in 1:10) bigt2 <- cbind( bigt2, rnorm(250) ) colnames(bigt2) <- paste('t',1:10,sep="") bigt2 or bigt3 <- matrix(rnorm(250*10),ncol=10) colnames(bigt3) <- paste('t',1:10,sep="") bigt3 HTH, Jorge On Fri, Apr 17, 2009 at 10:12 PM, Brendan Morse wrote: > Hi everyone, I am trying to accomplish a small task that is giving me quite > a headache. I would like to automatically generate a series of matrices and > give them successive names. Here is what I thought at first: > > t1<-matrix(0, nrow=250, ncol=1) > > for(i in 1:10){ >t1[i]<-rnorm(250) > } > > What I intended was that the loop would create 10 different matrices with a > single column of 250 values randomly selected from a normal distribution, > and that they would be labeled t11, t12, t13, t14 etc. > > Can anyone steer me in the right direction with this one? > > Thanks! > Brendan > > __ > 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] Loop question
Brendan Morse wrote: > > Hi everyone, I am trying to accomplish a small task that is giving me > quite a headache. I would like to automatically generate a series of > matrices and give them successive names. Here is what I thought at > first: > > t1<-matrix(0, nrow=250, ncol=1) > > for(i in 1:10){ > t1[i]<-rnorm(250) > } > > What I intended was that the loop would create 10 different matrices > with a single column of 250 values randomly selected from a normal > distribution, and that they would be labeled t11, t12, t13, t14 etc. > I think you're basically looking for http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f or http://wiki.r-project.org/rwiki/doku.php?id=tips:data-misc:create_var_names but see the comments in both places that indicate why it may be easier to do this as a list. for(i in 1:10){ assign(paste("t1",i,sep=""),matrix(rnorm(250))) } -- View this message in context: http://www.nabble.com/Loop-question-tp23108752p23108788.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] Loop question
Brendan, Matrix is atomic. Once you define t1 in matrix, t1[1]=0 rather than the whole column. I would just convert t1 to a data frame, which is a special list, by adding t1<- data.frame(t1). Now t1[1] represents the whole column. Then you can use your loop to add more columns. Jun On Fri, Apr 17, 2009 at 9:12 PM, Brendan Morse wrote: > Hi everyone, I am trying to accomplish a small task that is giving me quite > a headache. I would like to automatically generate a series of matrices and > give them successive names. Here is what I thought at first: > > t1<-matrix(0, nrow=250, ncol=1) > > for(i in 1:10){ >t1[i]<-rnorm(250) > } > > What I intended was that the loop would create 10 different matrices with a > single column of 250 values randomly selected from a normal distribution, > and that they would be labeled t11, t12, t13, t14 etc. > > Can anyone steer me in the right direction with this one? > > Thanks! > Brendan > > __ > 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. > -- Jun Shen PhD PK/PD Scientist BioPharma Services Millipore Corporation 15 Research Park Dr. St Charles, MO 63304 Direct: 636-720-1589 [[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] Loop question
On Fri, Apr 17, 2009 at 10:12 PM, Brendan Morse wrote: > ...I would like to automatically generate a series of matrices and > give them successive names. Here is what I thought at first: > > t1<-matrix(0, nrow=250, ncol=1) > > for(i in 1:10){ > t1[i]<-rnorm(250) > } > > What I intended was that the loop would create 10 different matrices with a > single column of 250 values randomly selected from a normal distribution, > and that they would be labeled t11, t12, t13, t14 etc. Very close. But since you've started out with a *matrix* t1, your assignments to t1[i] will assign to parts of the matrix. To correct this, all you need to do is initialize t1 as a *list of matrices* or (even better) as an *empty list*, like this: t1 <- list() and then assign to *elements* of the list (using [[ ]] notation), not to *sublists* of the list (which is what [ ] notation means in R), like this: for(i in 1:10){ t1[[i]] <- rnorm(250) } Is that what you had in mind? -s __ 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] loop help
On 17/06/2009, at 3:12 PM, dde...@sciborg.uwaterloo.ca wrote: Hi all, I'm stuck trying to get syntax correct for the follwing type of loop. I would like to find the column with the largest value in a given row, and create a new column with a categorical variable indicating which column the highest value of "i" comes from. too=data.frame(A=rnorm(10,1),B=rnorm(10,2),C=rnorm(10,1.5)) too$large=0 too$large=for (i in 1:length(too[,c(1,2,3)])) { if (too$A[i] > too$B[i] & too$C[i]) {too$large[i]=1} else if (too$B[i] > too$A[i] & too$C[i]) {too$large[i]=2} else if (too$C[i] > too$A[i] & too$B[i]) {too$large[i]=3}} Ultiamtely this is not working for me, any hints would be much appreciated! Hints: (1) Use the tools and facilities that R provides. Take some time to learn about them. It will pay off, big-time. (2) Whatever anyone else may tell you, ***DON'T*** use ``='' for assignment. That way lies peril. Use ``<-'' as God intended. :-) (3) The solution to your immediate problem is exemplified by: set.seed(42) too <- data.frame(A=rnorm(10,1),B=rnorm(10,2),C=rnorm(10,1.5)) too$large <- apply(too,1,which.max) too A B C large 1 2.3709584 3.3048697 1.1933614 2 2 0.4353018 4.2866454 -0.2813084 2 3 1.3631284 0.6111393 1.3280826 1 4 1.6328626 1.7212112 2.7146747 3 5 1.4042683 1.8666787 3.3951935 3 6 0.8938755 2.6359504 1.0695309 2 7 2.5115220 1.7157471 1.2427306 1 8 0.9053410 -0.6564554 -0.2631631 1 9 3.0184237 -0.4404669 1.9600974 1 10 0.9372859 3.3201133 0.8600051 2 cheers, Rolf Turner ## Attention:\ This e-mail message is privileged and confid...{{dropped:9}} __ 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] loop with files
Alfredo Alessandrini wrote: > I'm trying to make a loop with many files... > > > >> library(dplR) >> >> files <- system("ls *.rwl", intern=TRUE) >> >> files >> > [1] "cimfasy.rwl" "rocquce.rwl" > >> for (i in files) {a <- read.rwl(i,header=0)} >> > There are 70 series > There are 21 series > >> class(a) >> > [1] "data.frame" > > > This loop import all the files rwl in a single data.frame ( a ). > > Can I import a single files to a single data.frame? like this: > > for (i in files) {cimfasy <- read.rwl(i,header=0)} > > for (i in files) {rocquce <- read.rwl(i,header=0)} > > > not easy to get what you really want. the first loop above does read each file separately and place it into a, but at each step it replaces the content of a with a new one. so a contains only the content of the last file, and the whole loop makes no sense. the other two loops do quite the same, just that now you have additional two variables filled with the contents of the same file, the last one on your list. makes no sense either. can you *explain* what the goal is? vQ __ 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] loop with files
Alfredo Alessandrini wrote: >> can you *explain* what the goal is? >> > > I want import any rwl files (cimfasy.rwl, rocquce.rwl, ...), in a > data.frame with the name like to name of file rwl: > > cimfasy.rwl -> cimfasy > > rocquce.rwl -> rocquce > > with this loop: > > >> library(dplR) >> >> files <- system("ls *.rwl", intern=TRUE) >> >> files >> > [1] "cimfasy.rwl" "rocquce.rwl" > >> for (i in files) {a <- read.rwl(i,header=0)} >> for (file in files) assign(gsub("\\.rwl$", "", file), read.rwl(file, header=0)) ?assign ?gsub vQ __ 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] loop with files
Hi, I am not sure this is what you want …. But alist <- list.files(path = "whatever path you have for your files", full.names = TRUE) Now you have a list with the names of your files …. Form each name you can make a variable name and assign that file …. fname <- substring(alist[i], first, last) n <- length(alist) resultList <- list() for( i in 1:n){ resultList[[i]] <- read.table(alist[i]) ### this only if the *.rwl is a kind of table …. I am not familiar with this extension so I have no idea how you read it in R } names(resultList) <- fname Now you have a list of your data named as you want ….. you have access to it or any of the list members I am not taking credit the question about using a list to name variables was put before and Greg Snow came up with the list() idea - i think. Hope this helps if this is what you want, Monica Message: 4 Date: Tue, 24 Jun 2008 12:37:44 +0200 From: Wacek Kusnierczyk Subject: Re: [R] loop with files To: R help Message-ID: Content-Type: text/plain; charset=ISO-8859-1 Alfredo Alessandrini wrote: >> can you *explain* what the goal is? >> > > I want import any rwl files (cimfasy.rwl, rocquce.rwl, ...), in a > data.frame with the name like to name of file rwl: > > cimfasy.rwl -> cimfasy > > rocquce.rwl -> rocquce > > with this loop: > > >> library(dplR) >> >> files <- system("ls *.rwl", intern=TRUE) >> >> files >> > [1] "cimfasy.rwl" "rocquce.rwl" > >> for (i in files) {a <- read.rwl(i,header=0)} >> for (file in files) assign(gsub("\\.rwl$", "", file), read.rwl(file, header=0)) ?assign ?gsub vQ _ The i’m Talkathon starts 6/24/08. For now, give amongst yourselves. __ 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] loop for multiple regressions
Dear all, I have the following data in excel: day1 y 1 2 3 2 3 x1 0.2 0.3 0.4 0.3 0.2 x2 7 3.4 2 8 6 day2 y 2 4 3 2 2 x1 0.4 0.5 0.3 0.3 0.2 x2 7 8 9.1 6 5 I have the following problems: first of all, when I ask R to read the file (with the package xlsReadWrite and the command read.xls) it has a problem with the fact that the left most corner is labelled the same way, so in order for it to work I need to do: day1 y1 1 2 3 2 3 x11 0.2 0.3 0.4 0.3 0.2 x21 7 3.4 2 8 6 day2 y2 2 4 3 2 2 x12 0.4 0.5 0.3 0.3 0.2 x22 7 8 9.1 6 5 Next I need to do the regression y~ x1+x2, for the different days. I have converted the above data in the form of a matrix and labelled it mat. The following loop works: results<-c(0,0,0,0,0) for (i in c(1,5)){ results[i]<-lm(mat[i,]~mat[i+1,]+mat[i+2,])} results And the results are: Warning messages: 1: In results[i] <- lm(mat[i, ] ~ mat[i + 1, ] + mat[i + 2, ]) : number of items to replace is not a multiple of replacement length 2: In results[i] <- lm(mat[i, ] ~ mat[i + 1, ] + mat[i + 2, ]) : number of items to replace is not a multiple of replacement length > results [[1]] (Intercept) mat[i + 1, ] mat[i + 2, ] 2.49184151.5151515 -0.1356220 [[2]] [1] 0 [[3]] [1] 0 [[4]] [1] 0 [[5]] (Intercept) mat[i + 1, ] mat[i + 2, ] -0.37419353.41935480.2580645 The method does work but it is not ideal. The problem is that the real data that I will be using will involve regressions of 20 or so variables over 3000 days. I also want to avoid finding the exact values that i should take inside the loop. Is there a better way of carrying out these regressions so that I do not need to relabel everything, the results are faster and it is clear and easy to isolate the results of the linear models for each day? Thank you very much everyone in advance, Regards, Denise [[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] loop does not work
Hi, I am new to R and am trying to do a loop but it seems not to run after one turn. What I want to do is subset my dataframe (extract one station and one day) to calculate and store the maxima that can then be plotted. I have an error message at the end of each loop: Error: unexpected '}' in "}" Here is my code: * datafile <- read.csv(file="all_stations_24h_at_rh_0701-0718.csv",head=TRUE,sep=",") #-build maxima vector maxima<-mat.or.vec(132,18) Temp<-mat.or.vec(1,24) regions<-levels(datafile$Region) stations<-levels(factor(datafile$Stn.Id)) days<-levels(datafile$Date) i=1 j=1 while(ihttps://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] loop with splitted data
Hi to all, seems to be simple, but I do not find the solution: What must I write for the splitted to get splitted$"3"$x and splitted$"3"$x y = c(rep(2,5),rep(3,5)) ma <- data.frame(x = 1:10, y=y ) splitted <- split(ma, ma$y) for (counter in (min(ma$y):max(ma$y))) { splitted$x } Regards Knut __ 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] Loop on vector name
[My previous message rejected, therefore I am sending same one with some modification] I have 3 vectors with object name : dat1, dat2, dat3 Now I want to create a loop, like : for (i in 1:3) { cat(sd(dati)) } How I can do this in R? Regards, __ 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] Loop with variable index
I have a list of 20 values. The first time through a loop I want to find the mean and stnd.dev. of the first two values; the second time through the loop I want to find the mean and stnd. dev. of the first 3 values, etc. until the last time through the loop I want to find the mean and stnd. dev. of all 20 values, so I end up with 19 means and stnd. deviations. How would I construct such a loop? Thanks. -- View this message in context: http://www.nabble.com/Loop-with-variable-index-tp15190661p15190661.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] loop with dates
Try this: weekdays(seq(fini,to = ffin, by='days')) or in a loop: sapply(as.character(seq(fini,to = ffin, by='days')), function(d)weekdays(as.Date(d))) On Fri, Dec 12, 2008 at 4:55 PM, Fernando Bizuet wrote: > Hello, > > I am trying to do a loop with dates, but when I try to use the index is not > a date. > > Fcorte <- as.Date('2008/11/30',format = "%Y/%m/%d") > fini <- Fcorte + 1 > ffin <- seq(fini,by='months',length=2)[2] - 1 > > for (i in seq(fini,to = ffin, by='days')) >print (weekdays(i)) # i doesn't a date > > How can I do a loop with dates and get the index of each date? are there a > method to convert the index i to date? > > > Thanks in advance. > >[[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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[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] loop with dates
Try iterating over the index rather than the value of each component: s <- seq(fini,to = ffin, by='days') for (i in seq_along(s)) print(s[[i]]) On Fri, Dec 12, 2008 at 1:55 PM, Fernando Bizuet wrote: > Hello, > > I am trying to do a loop with dates, but when I try to use the index is not > a date. > > Fcorte <- as.Date('2008/11/30',format = "%Y/%m/%d") > fini <- Fcorte + 1 > ffin <- seq(fini,by='months',length=2)[2] - 1 > > for (i in seq(fini,to = ffin, by='days')) >print (weekdays(i)) # i doesn't a date > > How can I do a loop with dates and get the index of each date? are there a > method to convert the index i to date? > > > Thanks in advance. > >[[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] loop with dates
> -Original Message- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of Fernando Bizuet > Sent: Friday, December 12, 2008 12:55 PM > To: r-help@r-project.org > Subject: [R] loop with dates > > Hello, > > I am trying to do a loop with dates, but when I try to use > the index is not > a date. See ?"for". That help page mentions the following which can clarify what to expect "... The variable 'var' has the same type as 'seq' ..." Small illustration, fac <- gl(5,1,labels=letters[1:5]) fac [1] a b c d e Levels: a b c d e typeof(fac) [1] "integer" for(i in fac) print(i) [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > >Fcorte <- as.Date('2008/11/30',format = "%Y/%m/%d") >fini <- Fcorte + 1 >ffin <- seq(fini,by='months',length=2)[2] - 1 > >for (i in seq(fini,to = ffin, by='days')) > print (weekdays(i)) # i doesn't a date typeof(ffin) [1] "double" As your index is no longer of class 'Date', you will get Error in UseMethod("weekdays") : no applicable method for "weekdays > > How can I do a loop with dates and get the index of each > date? are there a > method to convert the index i to date? Here's one way dd <- seq(fini,to = ffin, by='days') for (i in seq_along(dd)) print(dd[i]) > > > Thanks in advance. > > [[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.
[R] Loop swith String replacement
Hi All, I'm trying to split my dataset, into multiple datasets that i'll analyse later, i wanted to do this dynamically as i might need to rerun the code later. I was looking at doing this via a loop, (Are other methods more appropriate? Would a function be better?) However i'm not sure in R how do do string replacement within the loop in order to create unique dataset names based on the number of 'Groups' i have Many thanks Mike my code is as follows: no.groups <-names(table(Conv$Group)) for (i in length(Conv$no.groups)) { groupi <- subset(Conv, Conv$Group == i) } Metal Secs cost Income stable Group 1 Chrome 6014 3.3458 1 2 2 Chrome 5110 1.8561 0 1 3 Chrome 2412 0.6304 0 1 4 Chrome 38 8 3.4183 1 2 5 Chrome 2512 2.7852 1 3 6 Chrome 6712 2.3866 1 1 7 Chrome 4012 4.2857 0 1 8 Chrome 5610 9.3205 1 1 9 Chrome 3212 3.8797 1 3 10 Chrome 7516 2.7031 1 3 11 Chrome 4615 11.2307 1 2 12 Chrome 5212 8.6696 1 2 13 Chrome 2212 1.7443 0 2 14 Chrome 6012 0.2253 0 2 15 Chrome 2414 4.3348 1 3 -- Michael Pearmain Senior Analytics Research Specialist Google UK Ltd Belgrave House 76 Buckingham Palace Road London SW1W 9TQ United Kingdom t +44 (0) 2032191684 [EMAIL PROTECTED] If you received this communication by mistake, please don't forward it to anyone else (it may contain confidential or privileged information), please erase all copies of it, including all attachments, and please let the sender know it went to the wrong person. Thanks. [[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] Loop on characters
megh wrote: > > suppose I have three vectors like : > > l1 = 1:4 > l2 = 4:9 > l3 = 16:67 > > now I want to construct a loop like : > > for (i in 1:3) >{ > count1[i] = length(li) # i.e. it will take l1, l2, l3 according to > value of i >} > Try this. There's probably a more elegant way to do it, but this works. l1 <- 1:4; l2 <- 4:9; l3 <- 16:67 count1 <- c( ) # start with an empty vector for (i in 1:3) count1[i] <- length(get(paste("l",i,sep=""))) count1 The call to paste( ) concatenates the letter "l" and value of i; they are separated by the null string (otherwise they would have the default blank separator between them). The call to get( ) fetches the object with that name. -- View this message in context: http://www.nabble.com/Loop-on-characters-tp21949173p21949383.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] Loop on characters
megh - The best way to organize similar objects in R is to put them into a list. If you keep this in mind when you're first organizing your data, it's no harder than giving each object a separate name. For example l = list(l1,l2,l3) The reason that this is a good idea in R is that functions like sapply, lapply, and mapply automatically operate on each element of a list, and return the answer in a suitable R object. (Note that in your example, you would get an error because you hadn't defined count1. And why should you?) So the answer you want is count1 = sapply(l,length) count1 [1] 4 6 52 Hope this helps. - Phil Spector Statistical Computing Facility Department of Statistics UC Berkeley spec...@stat.berkeley.edu On Tue, 10 Feb 2009, megh wrote: Hi, suppose I have three vectors like : l1 = 1:4 l2 = 4:9 l3 = 16:67 now I want to construct a loop like : for (i in 1:3) { count1[i] = length(li) # i.e. it will take l1, l2, l3 according to value of i } Can anyone please tell me how to do that? Regards, -- View this message in context: http://www.nabble.com/Loop-on-characters-tp21949173p21949173.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@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] loop does not work
You are missing a right paren in this line: >while (jhttp://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] loop with splitted data
Is this what you want: > y = c(rep(2,5),rep(3,5)) > ma <- data.frame(x = 1:10, y=y ) > splitted <- split(ma, ma$y) > for (counter in (min(ma$y):max(ma$y))) + { + cat(counter, ":", splitted[[as.character(counter)]]$x, '\n') + } 2 : 1 2 3 4 5 3 : 6 7 8 9 10 On Tue, Aug 26, 2008 at 6:37 AM, Knut Krueger <[EMAIL PROTECTED]> wrote: > Hi to all, > seems to be simple, but I do not find the solution: > What must I write for the splitted to get > > splitted$"3"$x and splitted$"3"$x > > y = c(rep(2,5),rep(3,5)) > ma <- data.frame(x = 1:10, y=y ) > splitted <- split(ma, ma$y) > for (counter in (min(ma$y):max(ma$y))) > { > splitted$x > } > > > Regards Knut > > __ > 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 Cincinnati, OH +1 513 646 9390 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.
Re: [R] loop with splitted data
jim holtman wrote: Is this what you want: y = c(rep(2,5),rep(3,5)) ma <- data.frame(x = 1:10, y=y ) splitted <- split(ma, ma$y) for (counter in (min(ma$y):max(ma$y))) + { + cat(counter, ":", splitted[[as.character(counter)]]$x, '\n') + } 2 : 1 2 3 4 5 3 : 6 7 8 9 10 But maybe this is what he really wanted: > lapply(splitted,"[[", "x") $`2` [1] 1 2 3 4 5 $`3` [1] 6 7 8 9 10 or even > split(ma$x, ma$y) $`2` [1] 1 2 3 4 5 $`3` [1] 6 7 8 9 10 -- O__ Peter Dalgaard Øster Farimagsgade 5, Entr.B c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~ - ([EMAIL PROTECTED]) FAX: (+45) 35327907 __ 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] loop with splitted data
Hi R users, I have a question which is some what related to this thread. Here is the setup: z is a list of lists, with no names. zz is same is z, but with names. with names on zz, I can crawl on the data with lapply, but I don't know how do the same on z (without names). Can someone help? ### === here is the code, which explains more clear of my problem x <- list(1:3,4:6) y <- list(11:13,14:16) z <- list(x,y) xx <- x names(xx) <- c("1","2") yy <- y names(yy) <- c("1","2") zz <- list(xx,yy) lapply(zz, "[[", "1") lapply(zz, "[[", "2") # Question: how can I get the same thing from z? # i.e. lapply(z, "[[", ), what is so that # I can get the same values as lapply(zz, "[[", "1"). # I tried =[[1]], =[1], ="[[". They all don't work. # I feel that I need a string or something to tell lapply what I want. This is a simplify version of my problem; in my case, I can't name all the sub-lists, please help. Thanks in advance, Gary -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Peter Dalgaard Sent: Tuesday, August 26, 2008 6:27 PM To: jim holtman Cc: r-help@r-project.org Subject: Re: [R] loop with splitted data jim holtman wrote: > Is this what you want: > > >> y = c(rep(2,5),rep(3,5)) >> ma <- data.frame(x = 1:10, y=y ) >> splitted <- split(ma, ma$y) >> for (counter in (min(ma$y):max(ma$y))) >> > + { > + cat(counter, ":", splitted[[as.character(counter)]]$x, '\n') > + } > 2 : 1 2 3 4 5 > 3 : 6 7 8 9 10 > > But maybe this is what he really wanted: > lapply(splitted,"[[", "x") $`2` [1] 1 2 3 4 5 $`3` [1] 6 7 8 9 10 or even > split(ma$x, ma$y) $`2` [1] 1 2 3 4 5 $`3` [1] 6 7 8 9 10 -- O__ Peter Dalgaard Øster Farimagsgade 5, Entr.B c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~ - ([EMAIL PROTECTED]) FAX: (+45) 35327907 __ 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. This message w/attachments (message) may be privileged, confidential or proprietary, and if you are not an intended recipient, please notify the sender, do not use or share it and delete it. Unless specifically indicated, this message is not an offer to sell or a solicitation of any investment products or other financial product or service, an official confirmation of any transaction, or an official statement of Merrill Lynch. Subject to applicable law, Merrill Lynch may monitor, review and retain e-communications (EC) traveling through its networks/systems. The laws of the country of each sender/recipient may impact the handling of EC, and EC may be archived, supervised and produced in countries other than the country in which you are located. This message cannot be guaranteed to be secure or error-free. This message is subject to terms available at the following link: http://www.ml.com/e-communications_terms/. By messaging with Merrill Lynch you consent to the foregoing. __ 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] loop with splitted data
Is this what you want: > lapply(z, '[[', 1) [[1]] [1] 1 2 3 [[2]] [1] 11 12 13 > lapply(z, '[[', 2) [[1]] [1] 4 5 6 [[2]] [1] 14 15 16 > On Wed, Sep 10, 2008 at 11:43 AM, Ling, Gary (Electronic Trading) <[EMAIL PROTECTED]> wrote: > Hi R users, I have a question which is some what related to this thread. > > Here is the setup: > z is a list of lists, with no names. > zz is same is z, but with names. > with names on zz, I can crawl on the data with lapply, but I don't know how > do the same on z (without names). Can someone help? > > > ### === here is the code, which explains more clear of my problem > x <- list(1:3,4:6) > y <- list(11:13,14:16) > z <- list(x,y) > > xx <- x > names(xx) <- c("1","2") > yy <- y > names(yy) <- c("1","2") > zz <- list(xx,yy) > > lapply(zz, "[[", "1") > lapply(zz, "[[", "2") > # Question: how can I get the same thing from z? > # i.e. lapply(z, "[[", ), what is so that > # I can get the same values as lapply(zz, "[[", "1"). > # I tried =[[1]], =[1], ="[[". They all don't work. > # I feel that I need a string or something to tell lapply what I want. > > This is a simplify version of my problem; in my case, I can't name all the > sub-lists, please help. > > Thanks in advance, > Gary > > > > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Peter Dalgaard > Sent: Tuesday, August 26, 2008 6:27 PM > To: jim holtman > Cc: r-help@r-project.org > Subject: Re: [R] loop with splitted data > > > jim holtman wrote: >> Is this what you want: >> >> >>> y = c(rep(2,5),rep(3,5)) >>> ma <- data.frame(x = 1:10, y=y ) >>> splitted <- split(ma, ma$y) >>> for (counter in (min(ma$y):max(ma$y))) >>> >> + { >> + cat(counter, ":", splitted[[as.character(counter)]]$x, '\n') >> + } >> 2 : 1 2 3 4 5 >> 3 : 6 7 8 9 10 >> >> > But maybe this is what he really wanted: > > > lapply(splitted,"[[", "x") > $`2` > [1] 1 2 3 4 5 > > $`3` > [1] 6 7 8 9 10 > > or even > > > split(ma$x, ma$y) > $`2` > [1] 1 2 3 4 5 > > $`3` > [1] 6 7 8 9 10 > > -- > O__ Peter Dalgaard Øster Farimagsgade 5, Entr.B > c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K > (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 > ~~ - ([EMAIL PROTECTED]) FAX: (+45) 35327907 > > __ > 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. > > > This message w/attachments (message) may be privileged, confidential or > proprietary, and if you are not an intended recipient, please notify the > sender, do not use or share it and delete it. Unless specifically indicated, > this message is not an offer to sell or a solicitation of any investment > products or other financial product or service, an official confirmation of > any transaction, or an official statement of Merrill Lynch. Subject to > applicable law, Merrill Lynch may monitor, review and retain e-communications > (EC) traveling through its networks/systems. The laws of the country of each > sender/recipient may impact the handling of EC, and EC may be archived, > supervised and produced in countries other than the country in which you are > located. This message cannot be guaranteed to be secure or error-free. This > message is subject to terms available at the following link: > http://www.ml.com/e-communications_terms/. By messaging with Merrill Lynch > you consent to the foregoing. > > __ > 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 Cincinnati, OH +1 513 646 9390 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.
Re: [R] loop with splitted data
YES! many many thanks, Jim. I know it'd be simple, yet I can't believe it's that simple. =) -gary -Original Message- From: jim holtman [mailto:[EMAIL PROTECTED] Sent: Wednesday, September 10, 2008 11:55 AM To: Ling, Gary (Electronic Trading) Cc: Peter Dalgaard; r-help@r-project.org Subject: Re: [R] loop with splitted data Is this what you want: > lapply(z, '[[', 1) [[1]] [1] 1 2 3 [[2]] [1] 11 12 13 > lapply(z, '[[', 2) [[1]] [1] 4 5 6 [[2]] [1] 14 15 16 > On Wed, Sep 10, 2008 at 11:43 AM, Ling, Gary (Electronic Trading) <[EMAIL PROTECTED]> wrote: > Hi R users, I have a question which is some what related to this thread. > > Here is the setup: > z is a list of lists, with no names. > zz is same is z, but with names. > with names on zz, I can crawl on the data with lapply, but I don't know how > do the same on z (without names). Can someone help? > > > ### === here is the code, which explains more clear of my problem > x <- list(1:3,4:6) > y <- list(11:13,14:16) > z <- list(x,y) > > xx <- x > names(xx) <- c("1","2") > yy <- y > names(yy) <- c("1","2") > zz <- list(xx,yy) > > lapply(zz, "[[", "1") > lapply(zz, "[[", "2") > # Question: how can I get the same thing from z? > # i.e. lapply(z, "[[", ), what is so that > # I can get the same values as lapply(zz, "[[", "1"). > # I tried =[[1]], =[1], ="[[". They all don't work. > # I feel that I need a string or something to tell lapply what I want. > > This is a simplify version of my problem; in my case, I can't name all the > sub-lists, please help. > > Thanks in advance, > Gary > > > > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Peter Dalgaard > Sent: Tuesday, August 26, 2008 6:27 PM > To: jim holtman > Cc: r-help@r-project.org > Subject: Re: [R] loop with splitted data > > > jim holtman wrote: >> Is this what you want: >> >> >>> y = c(rep(2,5),rep(3,5)) >>> ma <- data.frame(x = 1:10, y=y ) >>> splitted <- split(ma, ma$y) >>> for (counter in (min(ma$y):max(ma$y))) >>> >> + { >> + cat(counter, ":", splitted[[as.character(counter)]]$x, '\n') >> + } >> 2 : 1 2 3 4 5 >> 3 : 6 7 8 9 10 >> >> > But maybe this is what he really wanted: > > > lapply(splitted,"[[", "x") > $`2` > [1] 1 2 3 4 5 > > $`3` > [1] 6 7 8 9 10 > > or even > > > split(ma$x, ma$y) > $`2` > [1] 1 2 3 4 5 > > $`3` > [1] 6 7 8 9 10 > > -- > O__ Peter Dalgaard Øster Farimagsgade 5, Entr.B > c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K > (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 > ~~ - ([EMAIL PROTECTED]) FAX: (+45) 35327907 > > __ > 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. > > > This message w/attachments (message) may be privileged, confidential or > proprietary, and if you are not an intended recipient, please notify the > sender, do not use or share it and delete it. Unless specifically indicated, > this message is not an offer to sell or a solicitation of any investment > products or other financial product or service, an official confirmation of > any transaction, or an official statement of Merrill Lynch. Subject to > applicable law, Merrill Lynch may monitor, review and retain e-communications > (EC) traveling through its networks/systems. The laws of the country of each > sender/recipient may impact the handling of EC, and EC may be archived, > supervised and produced in countries other than the country in which you are > located. This message cannot be guaranteed to be secure or error-free. This > message is subject to terms available at the following link: > http://www.ml.com/e-communications_terms/. By messaging with Merrill Lynch > you consent to the foregoing. > > __ > 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 Cincinnati, OH +1 513 646 9390 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.
Re: [R] Loop on vector name
Try this: sapply(ls(patt="^dat[0-9]"), function(x)sd(get(x))) On Wed, Sep 17, 2008 at 8:50 AM, Megh Dal <[EMAIL PROTECTED]> wrote: > [My previous message rejected, therefore I am sending same one with some > modification] > > I have 3 vectors with object name : dat1, dat2, dat3 > > Now I want to create a loop, like : > > for (i in 1:3) > { >cat(sd(dati)) > } > > How I can do this in R? > > Regards, > > __ > 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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[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] Loop on vector name
you need to get(), e.g., try this: dat1 <- rnorm(5) dat2 <- rnorm(6) dat3 <- rnorm(7) lis <- lapply(paste("dat", 1:3, sep = ""), get) lis sapply(lis, sd) I hope it helps. Best, Dimitris Megh Dal wrote: [My previous message rejected, therefore I am sending same one with some modification] I have 3 vectors with object name : dat1, dat2, dat3 Now I want to create a loop, like : for (i in 1:3) { cat(sd(dati)) } How I can do this in R? Regards, __ 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. -- Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014 __ 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] Loop on vector name
Others have answered the question that you asked (it is also a variation of Faq 7.21), but here is an answer to the question that you should have asked: When working with datasets like this, it is better to create a list rather than separate objects with names like dat1, dat2, etc. For example: > mydat <- list(dat1=rnorm(10), dat2=rnorm(25), dat3=runif(100)) Now your loop can be: > for(i in 1:3) cat( sd( mydat[[i]] ) ) Or even simpler: > sapply( mydat, sd ) And when you are through with the data, you only need to delete one object, or copy one object, or save one object, etc. Hope this helps, > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > project.org] On Behalf Of Megh Dal > Sent: Wednesday, September 17, 2008 5:51 AM > To: [EMAIL PROTECTED] > Subject: [R] Loop on vector name > > [My previous message rejected, therefore I am sending same one with > some modification] > > I have 3 vectors with object name : dat1, dat2, dat3 > > Now I want to create a loop, like : > > for (i in 1:3) >{ > cat(sd(dati)) >} > > How I can do this in R? > > Regards, > > __ > 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] Loop on vector name
Thanks for this mail. It runs perfectly, but now I stuck on how to convert the result in a vector format for further matrix-compputation. e.g. How to convert "sapply(lis, sd)" to vector? --- On Wed, 9/17/08, Dimitris Rizopoulos <[EMAIL PROTECTED]> wrote: > From: Dimitris Rizopoulos <[EMAIL PROTECTED]> > Subject: Re: [R] Loop on vector name > To: [EMAIL PROTECTED] > Cc: [EMAIL PROTECTED] > Date: Wednesday, September 17, 2008, 5:32 PM > you need to get(), e.g., try this: > > dat1 <- rnorm(5) > dat2 <- rnorm(6) > dat3 <- rnorm(7) > > lis <- lapply(paste("dat", 1:3, sep = > ""), get) > lis > sapply(lis, sd) > > > I hope it helps. > > Best, > Dimitris > > > Megh Dal wrote: > > [My previous message rejected, therefore I am sending > same one with some modification] > > > > I have 3 vectors with object name : dat1, dat2, dat3 > > > > Now I want to create a loop, like : > > > > for (i in 1:3) > >{ > > cat(sd(dati)) > >} > > > > How I can do this in R? > > > > Regards, > > > > __ > > 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. > > > > -- > Dimitris Rizopoulos > Assistant Professor > Department of Biostatistics > Erasmus Medical Center > > Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands > Tel: +31/(0)10/7043478 > Fax: +31/(0)10/7043014 __ 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] Loop on vector name
oh god!! I used lapply() instead sapply(). Now it is ok. Thank you so much. By the way after a long time I saw your post. Hope you are well and everything going on fine :) --- On Fri, 9/19/08, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > From: [EMAIL PROTECTED] <[EMAIL PROTECTED]> > Subject: Re: [R] Loop on vector name > To: [EMAIL PROTECTED] > Date: Friday, September 19, 2008, 11:20 AM > hi: i'm not sure if i'm understanding your question > because the sapply > output is a vector. see below. > > > dat1 <- rnorm(5) > dat2 <- rnorm(6) > dat3 <- rnorm(7) > > lis <- lapply(paste("dat", 1:3, sep = > ""), get) > lis > output <- sapply(lis, sd) > print(output) > print(str(output)) > > > > On Fri, Sep 19, 2008 at 1:44 AM, Megh Dal wrote: > > > Thanks for this mail. It runs perfectly, but now I > stuck on how to > > convert the result in a vector format for further > matrix-compputation. > > e.g. How to convert "sapply(lis, sd)" to > vector? > > > > > > > > --- On Wed, 9/17/08, Dimitris Rizopoulos > <[EMAIL PROTECTED]> > > wrote: > > > >> From: Dimitris Rizopoulos > <[EMAIL PROTECTED]> > >> Subject: Re: [R] Loop on vector name > >> To: [EMAIL PROTECTED] > >> Cc: [EMAIL PROTECTED] > >> Date: Wednesday, September 17, 2008, 5:32 PM > >> you need to get(), e.g., try this: > >> > >> dat1 <- rnorm(5) > >> dat2 <- rnorm(6) > >> dat3 <- rnorm(7) > >> > >> lis <- lapply(paste("dat", 1:3, sep = > >> ""), get) > >> lis > >> sapply(lis, sd) > >> > >> > >> I hope it helps. > >> > >> Best, > >> Dimitris > >> > >> > >> Megh Dal wrote: > >>> [My previous message rejected, therefore I am > sending > >> same one with some modification] > >>> > >>> I have 3 vectors with object name : dat1, > dat2, dat3 > >>> > >>> Now I want to create a loop, like : > >>> > >>> for (i in 1:3) > >>>{ > >>> cat(sd(dati)) > >>>} > >>> > >>> How I can do this in R? > >>> > >>> Regards, > >>> > >>> __ > >>> 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. > >>> > >> > >> -- > >> Dimitris Rizopoulos > >> Assistant Professor > >> Department of Biostatistics > >> Erasmus Medical Center > >> > >> Address: PO Box 2040, 3000 CA Rotterdam, the > Netherlands > >> Tel: +31/(0)10/7043478 > >> Fax: +31/(0)10/7043014 > > > > __ > > 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] Loop with variable index
On 31/01/2008, at 8:58 AM, cvandy wrote: > > I have a list of 20 values. ***NO***! You have (or should have) a *vector* of 20 values. Vectors and lists are different concepts. Learn and understand the difference, else the world will come to an end. > The first time through a loop I want to find the > mean and stnd.dev. of the first two values; the second time through > the loop > I want to find the mean and stnd. dev. of the first 3 values, etc. > until > the last time through the loop I want to find the mean and stnd. > dev. of all > 20 values, so I end up with 19 means and stnd. deviations. Why (on earth) would you want to do this? > How would I construct such a loop? Let the vector be ``x''. mns <- list() sds <- list() for(i in 2:20) { mns[[i-1]] <- mean(x[1:i]) sds[[i-1]] <- sd(x[1:i]) } mns <- unlist(mns) sds <- unlist(sds) will do what you want. cheers, Rolf Turner ## Attention:\ This e-mail message is privileged and confid...{{dropped:9}} __ 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] Loop with variable index
Try this: x <- rnorm(20) sapply(c("sd", "mean"), function(fun)lapply(lapply(lapply(2:20, seq, from=1), function(.x)x[.x]), fun)) On 30/01/2008, cvandy <[EMAIL PROTECTED]> wrote: > > I have a list of 20 values. The first time through a loop I want to find the > mean and stnd.dev. of the first two values; the second time through the loop > I want to find the mean and stnd. dev. of the first 3 values, etc. until > the last time through the loop I want to find the mean and stnd. dev. of all > 20 values, so I end up with 19 means and stnd. deviations. > How would I construct such a loop? > Thanks. > -- > View this message in context: > http://www.nabble.com/Loop-with-variable-index-tp15190661p15190661.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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O __ 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] Loop with variable index
a cleaner code would be: sapply(2:20, function(i) c(mean=mean(x[1:i]), sd=sd(x[1:i]))) b On Jan 30, 2008, at 3:16 PM, Henrique Dallazuanna wrote: Try this: x <- rnorm(20) sapply(c("sd", "mean"), function(fun)lapply(lapply(lapply(2:20, seq, from=1), function(.x)x[.x]), fun)) On 30/01/2008, cvandy <[EMAIL PROTECTED]> wrote: I have a list of 20 values. The first time through a loop I want to find the mean and stnd.dev. of the first two values; the second time through the loop I want to find the mean and stnd. dev. of the first 3 values, etc. until the last time through the loop I want to find the mean and stnd. dev. of all 20 values, so I end up with 19 means and stnd. deviations. How would I construct such a loop? Thanks. -- View this message in context: http://www.nabble.com/Loop-with-variable-index-tp15190661p15190661.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. -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O __ 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] Loop with variable index
y <- sort(rnorm(20)) # say... m <- s <- numeric(19) for(i in 2:20) { m[i-1] <- mean(y[1:i]) s[i-1] <- sd(y[1:i]) } Easy peasy, ... Bill Venables CSIRO Laboratories PO Box 120, Cleveland, 4163 AUSTRALIA Office Phone (email preferred): +61 7 3826 7251 Fax (if absolutely necessary): +61 7 3826 7304 Mobile: +61 4 8819 4402 Home Phone: +61 7 3286 7700 mailto:[EMAIL PROTECTED] http://www.cmis.csiro.au/bill.venables/ -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of cvandy Sent: Thursday, 31 January 2008 5:59 AM To: r-help@r-project.org Subject: [R] Loop with variable index I have a list of 20 values. The first time through a loop I want to find the mean and stnd.dev. of the first two values; the second time through the loop I want to find the mean and stnd. dev. of the first 3 values, etc. until the last time through the loop I want to find the mean and stnd. dev. of all 20 values, so I end up with 19 means and stnd. deviations. How would I construct such a loop? Thanks. -- View this message in context: http://www.nabble.com/Loop-with-variable-index-tp15190661p15190661.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@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] Loop with variable index
csiro.au> writes: > > y <- sort(rnorm(20)) # say... > > m <- s <- numeric(19) > > for(i in 2:20) { > m[i-1] <- mean(y[1:i]) > s[i-1] <- sd(y[1:i]) > } > -Original Message- > On Behalf Of cvandy > Subject: [R] Loop with variable index > I have a list of 20 values. The first time through a loop I want to > find the > mean and stnd.dev. of the first two values; the second time through the > loop I want to find the mean and stnd. dev. of the first 3 values, etc. > until the last time through the loop I want to find the mean and stnd. dev. > of > all 20 values, so I end up with 19 means and stnd. deviations. > How would I construct such a loop? > Thanks. Just for an alternative to some of the sapply solutions, the means can also be obtained with (cumsum(y)/(1:length(y)))[-1] ken __ 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] Loop swith String replacement
Try this: split(Conv, Conv$Group) On Fri, Dec 5, 2008 at 11:28 AM, Michael Pearmain <[EMAIL PROTECTED]>wrote: > Hi All, > I'm trying to split my dataset, into multiple datasets that i'll analyse > later, i wanted to do this dynamically as i might need to rerun the code > later. > I was looking at doing this via a loop, (Are other methods more > appropriate? > Would a function be better?) > > However i'm not sure in R how do do string replacement within the loop in > order to create unique dataset names based on the number of 'Groups' i have > > Many thanks > > Mike > > my code is as follows: > > no.groups <-names(table(Conv$Group)) > for (i in length(Conv$no.groups)) > { > groupi <- subset(Conv, Conv$Group == i) > } > > > Metal Secs cost Income stable Group > 1 Chrome 6014 3.3458 1 2 > 2 Chrome 5110 1.8561 0 1 > 3 Chrome 2412 0.6304 0 1 > 4 Chrome 38 8 3.4183 1 2 > 5 Chrome 2512 2.7852 1 3 > 6 Chrome 6712 2.3866 1 1 > 7 Chrome 4012 4.2857 0 1 > 8 Chrome 5610 9.3205 1 1 > 9 Chrome 3212 3.8797 1 3 > 10 Chrome 7516 2.7031 1 3 > 11 Chrome 4615 11.2307 1 2 > 12 Chrome 5212 8.6696 1 2 > 13 Chrome 2212 1.7443 0 2 > 14 Chrome 6012 0.2253 0 2 > 15 Chrome 2414 4.3348 1 3 > > > > > -- > Michael Pearmain > Senior Analytics Research Specialist > > > Google UK Ltd > Belgrave House > 76 Buckingham Palace Road > London SW1W 9TQ > United Kingdom > t +44 (0) 2032191684 > [EMAIL PROTECTED] > > If you received this communication by mistake, please don't forward it to > anyone else (it may contain confidential or privileged information), please > erase all copies of it, including all attachments, and please let the > sender > know it went to the wrong person. Thanks. > >[[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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[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] Loop over several Garch-models
Dear all, I'm using R 2.8.1 on Windows XP. I want to loop over several garch-models to evaluate the best model-fit. After loading the package fGarch I execute the following loop: For(i in 1:5){ for(j in 1:5){ garchFit(~ arma(0,0) + garch(i,j), stetige_renditen[,7], cond.dist="sged", trace=F) } } Where "stetige_renditen[,7]" are the continously compounded returns of the FX â¬/$ 2007 - 2008. Unfortunately I get the following error: [1] "data" "i""j" [1] "data" Fehler in .garchArgsParser(formula = formula, data = data, trace = FALSE) : Formula and data units do not match. On top the time series is not stationary. So any advice to choose another model? I think IGARCH is not so good... Any help about the code and the non-statioarity-thing would be very appreciated. Kind regards, Thomas [[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] loop problem for extract coefficients
Dear R users, I have problem with extracting coefficients from a object. Here, X (predictor)and Y (response) are two matrix , I am regressing X ( dimensions 10 x 20) on each of columns of Y[,1] (10 x 1) and want to store the coefficient values. I have performed a Elastic Net regression and I want to store the coeffcients in each iteration. I got an error message . I do not know where is the problem Please help me. Thanks *Code:* --- library(elasticnet) X<-matrix(rnorm(200),ncol=20) Y<-matrix(rnorm(200),ncol=20) loop <- 20 size <- 20 enres<-matrix(nrow = size, ncol = loop) fit<-matrix(nrow = size, ncol = loop) store<-matrix(nrow = size, ncol = loop) for(j in 1: 10) print (paste(j,"/200",sep="")) { enres<-enet(x=X,y=Y[,j],lambda=1,normalize=TRUE,intercept=TRUE) fit<-predict.enet(enres, X, type="coefficients") store[,j]<-fit$coefficients } > library(elasticnet) Loading required package: lars > X<-matrix(rnorm(200),ncol=20) > Y<-matrix(rnorm(200),ncol=20) > > loop <- 20 > size <- 20 > > enres<-matrix(nrow = size, ncol = loop) > fit<-matrix(nrow = size, ncol = loop) > store<-matrix(nrow = size, ncol = loop) > > for(j in 1: 10) + print (paste(j,"/200",sep="")) [1] "1/200" [1] "2/200" [1] "3/200" [1] "4/200" [1] "5/200" [1] "6/200" [1] "7/200" [1] "8/200" [1] "9/200" [1] "10/200" > { + enres<-enet(x=X,y=Y[,j],lambda=1,normalize=TRUE,intercept=TRUE) + fit<-predict.enet(enres, X, type="coefficients") + store[,j]<-fit$coefficients + } *Error in store[, j] <- fit$coefficients : number of items to replace is not a multiple of replacement length > * [[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] Loop avoidance and logical subscripts
Hello! I'm writing a script with a lot of loops and it executes really slowly over huge amounts of data. I assume it's because I don't know how to avoid using loops. Logical subscripts are more desirable, but I don't know how to implement them. One example of that issue: library(seqinr) GCsequence <- vector() for( i in 1:(length(data$sequence))) { c(GCsequence,GC(s2c(data$sequence[i])))->data$GCsequence[i] } rm(GCsequence) How should I speed up that? Thank you, Retama -- View this message in context: http://www.nabble.com/Loop-avoidance-and-logical-subscripts-tp23652935p23652935.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] loop with splitted data -solved
Thank you for the hints, finally I was looking for the substitution of splitted$"2" to splitted[[as.character(counter)]] I did not know that I can substitute f.e the $"2" with [[2]] or/and $y (second column) with [[2]] Knut __ 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] Loop avoidance in simulating a vector
All, I'd like to simulate a vector that is formed from many distinct distributions and avoid a loop if possible. E.g, consider: mu = c(1, 2, 3) sigma = c(1, 2, 3) n = c(10, 10, 10) And we simulate a vector of length 30 that consists of N(mu[i], sigma[i]) distributed data, each of length n[i]. Of course for just three groups we can simply write it out as: DV = c(rnorm(n[1], mu[1], sigma[1]), rnorm(n[2], mu[2], sigma[2]), rnorm(n[3], mu[3], sigma[3]) ) For many groups we can use a loop (assuming equal numbers per group): n = n[1] DV = numeric(N*n) for (i in 1:N) { DV[(n*i - (n-1)): (n*i)] = rnorm(n, mu[i], sigma[i]) } Is there any way to do the general cas without using a loop? Cheers, David __ 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] loop problem for extract coefficients
Perhaps your loop should be more than just a print statement. That works fine! You need to place the print statement after the '{', not before it. fit$coefficients is a 21 x 20 array (the rows are lablelled 0 to 20) and you are trying to put it in the jth *column* of a 20 x 20 matrix. Not surprisingly it does not fit. Perhaps you need to know more about just what it is this software is doing. Bill Venables http://www.cmis.csiro.au/bill.venables/ -Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Alex Roy Sent: Monday, 6 April 2009 12:49 AM To: r-help@r-project.org Subject: [R] loop problem for extract coefficients Dear R users, I have problem with extracting coefficients from a object. Here, X (predictor)and Y (response) are two matrix , I am regressing X ( dimensions 10 x 20) on each of columns of Y[,1] (10 x 1) and want to store the coefficient values. I have performed a Elastic Net regression and I want to store the coeffcients in each iteration. I got an error message . I do not know where is the problem Please help me. Thanks *Code:* --- library(elasticnet) X<-matrix(rnorm(200),ncol=20) Y<-matrix(rnorm(200),ncol=20) loop <- 20 size <- 20 enres<-matrix(nrow = size, ncol = loop) fit<-matrix(nrow = size, ncol = loop) store<-matrix(nrow = size, ncol = loop) for(j in 1: 10) print (paste(j,"/200",sep="")) { enres<-enet(x=X,y=Y[,j],lambda=1,normalize=TRUE,intercept=TRUE) fit<-predict.enet(enres, X, type="coefficients") store[,j]<-fit$coefficients } > library(elasticnet) Loading required package: lars > X<-matrix(rnorm(200),ncol=20) > Y<-matrix(rnorm(200),ncol=20) > > loop <- 20 > size <- 20 > > enres<-matrix(nrow = size, ncol = loop) > fit<-matrix(nrow = size, ncol = loop) > store<-matrix(nrow = size, ncol = loop) > > for(j in 1: 10) + print (paste(j,"/200",sep="")) [1] "1/200" [1] "2/200" [1] "3/200" [1] "4/200" [1] "5/200" [1] "6/200" [1] "7/200" [1] "8/200" [1] "9/200" [1] "10/200" > { + enres<-enet(x=X,y=Y[,j],lambda=1,normalize=TRUE,intercept=TRUE) + fit<-predict.enet(enres, X, type="coefficients") + store[,j]<-fit$coefficients + } *Error in store[, j] <- fit$coefficients : number of items to replace is not a multiple of replacement length > * [[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] loop problem for extract coefficients
Hi Alex, On Sun, April 5, 2009 16:49, Alex Roy wrote: > Dear R users, > I have problem with extracting coefficients from a > object. Here, X (predictor)and Y (response) are two matrix , I am > regressing > X ( dimensions 10 x 20) on each of columns of Y[,1] (10 x 1) and want to > store the coefficient values. I have performed a Elastic Net regression > and > I want to store the coeffcients in each iteration. I got an error message > . > I do not know where is the problem Please help me. > > Thanks > > > > *Code:* > > --- > library(elasticnet) > X<-matrix(rnorm(200),ncol=20) > Y<-matrix(rnorm(200),ncol=20) > loop <- 20 > size <- 20 > enres<-matrix(nrow = size, ncol = loop) > fit<-matrix(nrow = size, ncol = loop) > store<-matrix(nrow = size, ncol = loop) > for(j in 1: 10) > print (paste(j,"/200",sep="")) > { > enres<-enet(x=X,y=Y[,j],lambda=1,normalize=TRUE,intercept=TRUE) > fit<-predict.enet(enres, X, type="coefficients") > store[,j]<-fit$coefficients > } > The problem is that only the print statement is inside the for loop. I would suggest: for(j in 1: 10) { # here the opening bracket print (paste(j,"/200",sep="")) # and not here! enres<-enet(x=X,y=Y[,j],lambda=1,normalize=TRUE,intercept=TRUE) fit<-predict.enet(enres, X, type="coefficients") store[,j]<-fit$coefficients } Hope this helps, Arien > >> library(elasticnet) > Loading required package: lars >> X<-matrix(rnorm(200),ncol=20) >> Y<-matrix(rnorm(200),ncol=20) >> >> loop <- 20 >> size <- 20 >> >> enres<-matrix(nrow = size, ncol = loop) >> fit<-matrix(nrow = size, ncol = loop) >> store<-matrix(nrow = size, ncol = loop) >> >> for(j in 1: 10) > + print (paste(j,"/200",sep="")) > [1] "1/200" > [1] "2/200" > [1] "3/200" > [1] "4/200" > [1] "5/200" > [1] "6/200" > [1] "7/200" > [1] "8/200" > [1] "9/200" > [1] "10/200" >> { > + enres<-enet(x=X,y=Y[,j],lambda=1,normalize=TRUE,intercept=TRUE) > + fit<-predict.enet(enres, X, type="coefficients") > + store[,j]<-fit$coefficients > + } > *Error in store[, j] <- fit$coefficients : > number of items to replace is not a multiple of replacement length >> * > > [[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. > -- drs. H.A. (Arien) Lam (Ph.D. student) Department of Physical Geography Faculty of Geosciences Utrecht University, The Netherlands __ 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] Loop avoidance and logical subscripts
Patrick Burns kindly provided an article about this issue called 'The R Inferno'. However, I will expand a little bit my question because I think it is not clear and, if I coud improve the code it will be more understandable to other users reading this messages when I will paste it :) In my example, I have a dataframe with several hundreds of DNA sequences in the column data$sequences (each value is a long string written in an alphabet of four characters, which are A, C, T and G). I'm trying to know parameter number of Gs plus Cs over the total [G+C/(A+T+C+G)] in each sequence. In example, data$sequence [1] is something like AATTCCCGG but a little bit longer, and, its G+C content is 0.69 . I need to compute a vector with all G+C contents (in my example, in data$GCsequence, in which data$GCsequence[1] is 0.69). So the question was if making a loop and a combination of values with c() or cbind() or with logical subscripts is ok or not. And which approach should produce better results in terms of efficiency (my script goes really slow). Thank you, Retama -- View this message in context: http://www.nabble.com/Loop-avoidance-and-logical-subscripts-tp23652935p23656703.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] Loop avoidance and logical subscripts
retama wrote: Patrick Burns kindly provided an article about this issue called 'The R Inferno'. However, I will expand a little bit my question because I think it is not clear and, if I coud improve the code it will be more understandable to other users reading this messages when I will paste it :) In my example, I have a dataframe with several hundreds of DNA sequences in the column data$sequences (each value is a long string written in an alphabet of four characters, which are A, C, T and G). I'm trying to know parameter number of Gs plus Cs over the total [G+C/(A+T+C+G)] in each sequence. In example, data$sequence [1] is something like AATTCCCGG but a little bit longer, and, its G+C content is 0.69 . I need to compute a vector with all G+C contents (in my example, in data$GCsequence, in which data$GCsequence[1] is 0.69). A very efficient way to do this is library(Biostrings) dna = DNAStringSet(data$sequence) alf = alphabetFrequency(dna, baseOnly=TRUE) gc = rowSums(alf[,c("G", "C")]) / rowSums(alf) this takes about .8 second for 3 million 36mers, for instance. Biostrings is installed with source('http://bioconductor.org/biocLite.R') biocLite('Biostrings') Martin So the question was if making a loop and a combination of values with c() or cbind() or with logical subscripts is ok or not. And which approach should produce better results in terms of efficiency (my script goes really slow). Thank you, Retama -- Martin Morgan Computational Biology / Fred Hutchinson Cancer Research Center 1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109 Location: Arnold Building M1 B861 Phone: (206) 667-2793 __ 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] Loop avoidance and logical subscripts
On 21-May-09 16:56:23, retama wrote: > Patrick Burns kindly provided an article about this issue called > 'The R Inferno'. However, I will expand a little bit my question > because I think it is not clear and, if I coud improve the code > it will be more understandable to other users reading this messages > when I will paste it :) > > In my example, I have a dataframe with several hundreds of DNA > sequences in the column data$sequences (each value is a long string > written in an alphabet of four characters, which are A, C, T and G). > I'm trying to know parameter number of Gs plus Cs over the total > [G+C/(A+T+C+G)] in each sequence. In example, data$sequence [1] is > something like AATTCCCGG but a little bit longer, and, its G+C > content is 0.69 . I need to compute a vector with all G+C contents > (in my example, in data$GCsequence, in which data$GCsequence[1] is > 0.69). > > So the question was if making a loop and a combination of values with > c() or cbind() or with logical subscripts is ok or not. And which > approach should produce better results in terms of efficiency (my > script goes really slow). > > Thank you, > Retama Perhaps the following could be the basis of your code for the bigger problem: S <- unlist(strsplit("AATTCCCGG","")) S # [1] "A" "A" "T" "T" "C" "C" "C" "G" "G" "G" "G" "G" "G" (sum((S=="C")|(S=="G"))) # [1] 9 (sum((S=="C")|(S=="G")))/length(S) # [1] 0.6923077 You could build a function on those lines, to evaluate what you want for any given string; and then apply() it to the elements (which are the separate character strings) of data$sequences (which is presumably a vector of character strings). Ted. E-Mail: (Ted Harding) Fax-to-email: +44 (0)870 094 0861 Date: 21-May-09 Time: 18:18:24 -- 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.
Re: [R] Loop avoidance and logical subscripts
Thank you! The script is now adapted to Biostrings and it is really fast! For example, it does: alph_sequence <- alphabetFrequency(data$sequence, baseOnly=TRUE) data$GCsequence <- rowSums(alph_sequence[,c("G", "C")]) / rowSums(alph_sequence) in the G+C computation. It also works amazingly fast in substring extraction (substring), reverse complement (reverseComplement sequences), palindromes search (findComplementedPalindromes) and so on. Now, my bottleneck is conventional string handling, because I have not found yet how to convert DNAStringSets to vector of chars. Now, I'm doing it by: dna <- vector() for (i in 1:length(dnaset)) { c(dna, toString(data$dnaset[[i]])) -> dna } Regards, Retama -- View this message in context: http://www.nabble.com/Loop-avoidance-and-logical-subscripts-tp23652935p23745814.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] Loop for the convergence of shape parameter
Hello, The likelihood includes two parameters to be estimated: lambda (=beta0+beta1*x) and alpha. The algorithm for the estimation is as following: 1) with alpha=0, estimate lambda (estimate beta0 and beta1 via GLM) 2) with lambda, estimate alpha via ML estimation 3) with updataed alpha, replicate 1) and 2) until alpha is converged to a value I coded 1) and 2) (it works), but faced some problems with the loop. It produced some errors. Is there someone to help me to figure this problem for the loop. Here are two codes: [I] one is for 1) and 2) (working), and [II] another one is for 1)-3) (making errors). Thank you in advance, Jin [I]for 1) and 2) (working) % data set alpha<-1 verpi<-c(5^alpha,10^alpha-5^alpha,14^alpha-10^alpha,18^alpha-14^alpha) r<-c(1,0,0,1) k<-c(3,2,2,2) x<-c(0.5,0.5,1.0,1.0) % estimate lambda (lambda=beta0+beta1*x) GLM_results <- glm(r/k ~ x, family=binomial(link='cloglog'), offset=log(verpi),weights=k) beta0<-GLM_results$coefficients[[1]] beta1]<-GLM_results$coefficients[[2]] lambda1<-beta0+beta1*x[1] lambda2<-beta0+beta1*x[2] % using lambda, estimate alpha (a=alpha) through ML estimation L<-function(a){ s1_f1<-(exp(-lambda1*(0^a-0^a))-exp(-lambda1*(5^a-0^a))) s2_f2<-(exp(-lambda1*(10^a)-lambda2*(14^a-10^a+14^a-14^a)) -exp(-lambda1*(10^a)-lambda2*(14^a-10^a+18^a-14^a))) logl<-log(s1_f1*s2_f2) return(-logl)} optim(1,L) alpha<-optim(1,L)$par } [II] for 1)-3) (making errors) alpha[1]<-1 beta0=rep(0,10) beta1=rep(0,10) lambda1=rep(0,10) lambda2=rep(0,10) lambda3=rep(0,10) lambda4=rep(0,10) verpi=rep(0,10) s1_f1=rep(0,10) s2_f2=rep(0,10) a=rep(0,10) logl=rep(0,10) beta0[1]=0 beta1[1]=0 lambda1[1]=0 lambda2[1]=0 lambda3[1]=0 lambda4[1]=0 verpi[1]=0 s1_f1[1]=0 s2_f2[1]=0 a[1]=1 logl[1]=0 for(i in 2:11){ verpi[i]<-c(5^alpha[i-1],10^alpha[i-1]-5^alpha[i-1],14^alpha[i-1]-10^alpha[i-1],18^alpha[i-1]-14^alpha[i-1]) r<-c(1,0,0,1) k<-c(3,2,2,2) x<-c(0.5,0.5,1.0,1.0) GLM_results <- glm(r/k ~ x, family=binomial(link='cloglog'), offset=log(verpi[i]),weights=k) GLM_results logLik(GLM_results[i]) beta0[i]<-GLM_results$coefficients[[1]] beta1[i]<-GLM_results$coefficients[[2]] beta0[i] beta1[i] lambda1[i]<-beta0[i]+beta1[i]*x[1] lambda2[i]<-beta0[i]+beta1[i]*x[2] lambda3[i]<-beta0[i]+beta1[i]*x[3] lambda4[i]<-beta0[i]+beta1[i]*x[4] lambda1[i] lambda2[i] lambda3[i] lambda4[i] L<-function(a){ s1_f1[i]<-(exp(-lambda1[i]*(0^a[i]-0^a[i]))-exp(-lambda1[i]*(5^a[i]-0^a[i]))) s2_f2[i]<-(exp(-lambda1[i]*(10^a[i])-lambda2[i]*(14^a[i]-10^a[i]+14^a[i]-14^a[i])) -exp(-lambda1*(10^a[i])-lambda2[i]*(14^a[i]-10^a[i]+18^a[i]-14^a[i]))) logl[i]<-log(s1_f1[i]*s2_f2[i]) return(-logl[i])} optim(1,L) alpha[i]<-optim(1,L)$par } alpha -- View this message in context: http://www.nabble.com/Loop-for-the-convergence-of-shape-parameter-tp19425959p19425959.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] Loop avoidance in simulating a vector
Have a look at mapply. -Christos > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of David Afshartous > Sent: Thursday, October 16, 2008 3:47 PM > To: r-help@r-project.org > Subject: [R] Loop avoidance in simulating a vector > > > > All, > > I'd like to simulate a vector that is formed from many > distinct distributions and avoid a loop if possible. E.g, consider: > > mu = c(1, 2, 3) > sigma = c(1, 2, 3) > n = c(10, 10, 10) > > And we simulate a vector of length 30 that consists of > N(mu[i], sigma[i]) > distributed data, each of length n[i]. Of course for just > three groups we > can simply write it out as: > > DV = c(rnorm(n[1], mu[1], sigma[1]), rnorm(n[2], mu[2], > sigma[2]), rnorm(n[3], mu[3], sigma[3]) ) > > For many groups we can use a loop (assuming equal numbers per group): > > n = n[1] > DV = numeric(N*n) > for (i in 1:N) { > DV[(n*i - (n-1)): (n*i)] = rnorm(n, mu[i], sigma[i]) > } > > Is there any way to do the general cas without using a loop? > > Cheers, > David > > __ > 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] Loop avoidance in simulating a vector
mapply is still a (disguised) loop (at the interpreted level). So other than improving code readability (always a good thing!), it shouldn't make much of an efficiency difference. A longer answer is: if all you're doing is a location-scale family of distributions, then creating a matrix of standard normal (or whatever) distributed data for all 1:N at once and then using matrix operations to multiply and add, say, so each column becomes your different distribution might be faster. This gets the loops down to C code. A shorter answer is: it's unlikely that any of this makes enough of a difference to be worth the effort. Random number generation is so efficient in R that "avoiding loops" rarely matters. Also see ?replicate for a way to perhaps write cleaner code (but still using hidden interpreted loops). -- Bert Gunter -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Christos Hatzis Sent: Thursday, October 16, 2008 1:06 PM To: 'David Afshartous'; r-help@r-project.org Subject: Re: [R] Loop avoidance in simulating a vector Have a look at mapply. -Christos > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of David Afshartous > Sent: Thursday, October 16, 2008 3:47 PM > To: r-help@r-project.org > Subject: [R] Loop avoidance in simulating a vector > > > > All, > > I'd like to simulate a vector that is formed from many > distinct distributions and avoid a loop if possible. E.g, consider: > > mu = c(1, 2, 3) > sigma = c(1, 2, 3) > n = c(10, 10, 10) > > And we simulate a vector of length 30 that consists of > N(mu[i], sigma[i]) > distributed data, each of length n[i]. Of course for just > three groups we > can simply write it out as: > > DV = c(rnorm(n[1], mu[1], sigma[1]), rnorm(n[2], mu[2], > sigma[2]), rnorm(n[3], mu[3], sigma[3]) ) > > For many groups we can use a loop (assuming equal numbers per group): > > n = n[1] > DV = numeric(N*n) > for (i in 1:N) { > DV[(n*i - (n-1)): (n*i)] = rnorm(n, mu[i], sigma[i]) > } > > Is there any way to do the general cas without using a loop? > > Cheers, > David > > __ > 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. __ 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] Loop avoidance in simulating a vector
Yes, but the difference is that the looping in mapply is done in C. There are no interpreted loops in mapply,as far as I can see. -Christos > -Original Message- > From: Bert Gunter [mailto:[EMAIL PROTECTED] > Sent: Thursday, October 16, 2008 4:13 PM > To: [EMAIL PROTECTED]; 'David Afshartous'; > r-help@r-project.org > Subject: RE: [R] Loop avoidance in simulating a vector > > mapply is still a (disguised) loop (at the interpreted > level). So other than improving code readability (always a > good thing!), it shouldn't make much of an efficiency difference. > > A longer answer is: if all you're doing is a location-scale > family of distributions, then creating a matrix of standard > normal (or whatever) distributed data for all 1:N at once and > then using matrix operations to multiply and add, say, so > each column becomes your different distribution might be > faster. This gets the loops down to C code. > > A shorter answer is: it's unlikely that any of this makes > enough of a difference to be worth the effort. Random number > generation is so efficient in R that "avoiding loops" rarely matters. > > Also see ?replicate for a way to perhaps write cleaner code > (but still using hidden interpreted loops). > > -- Bert Gunter > > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of Christos Hatzis > Sent: Thursday, October 16, 2008 1:06 PM > To: 'David Afshartous'; r-help@r-project.org > Subject: Re: [R] Loop avoidance in simulating a vector > > Have a look at mapply. > > -Christos > > > -Original Message- > > From: [EMAIL PROTECTED] > > [mailto:[EMAIL PROTECTED] On Behalf Of David Afshartous > > Sent: Thursday, October 16, 2008 3:47 PM > > To: r-help@r-project.org > > Subject: [R] Loop avoidance in simulating a vector > > > > > > > > All, > > > > I'd like to simulate a vector that is formed from many distinct > > distributions and avoid a loop if possible. E.g, consider: > > > > mu = c(1, 2, 3) > > sigma = c(1, 2, 3) > > n = c(10, 10, 10) > > > > And we simulate a vector of length 30 that consists of N(mu[i], > > sigma[i]) > > distributed data, each of length n[i]. Of course for just > > three groups we > > can simply write it out as: > > > > DV = c(rnorm(n[1], mu[1], sigma[1]), rnorm(n[2], mu[2], sigma[2]), > > rnorm(n[3], mu[3], sigma[3]) ) > > > > For many groups we can use a loop (assuming equal numbers > per group): > > > > n = n[1] > > DV = numeric(N*n) > > for (i in 1:N) { > > DV[(n*i - (n-1)): (n*i)] = rnorm(n, mu[i], sigma[i]) > > } > > > > Is there any way to do the general cas without using a loop? > > > > Cheers, > > David > > > > __ > > 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. > > > __ 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] Loop avoidance in simulating a vector
If you want to avoid using a loop, rather than coding a loop, then someting like: DV <- rnorm(sum(n)) DV <- DV * rep(sigma, times=n) + rep(mu, times=n) will achieve the same as the loop you specified, but generalised to non-constant n. HTH Ray Brownrigg On Fri, 17 Oct 2008, Bert Gunter wrote: > mapply is still a (disguised) loop (at the interpreted level). So other > than improving code readability (always a good thing!), it shouldn't make > much of an efficiency difference. > > A longer answer is: if all you're doing is a location-scale family of > distributions, then creating a matrix of standard normal (or whatever) > distributed data for all 1:N at once and then using matrix operations to > multiply and add, say, so each column becomes your different distribution > might be faster. This gets the loops down to C code. > > A shorter answer is: it's unlikely that any of this makes enough of a > difference to be worth the effort. Random number generation is so efficient > in R that "avoiding loops" rarely matters. > > Also see ?replicate for a way to perhaps write cleaner code (but still > using hidden interpreted loops). > > -- Bert Gunter > > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On > Behalf Of Christos Hatzis > Sent: Thursday, October 16, 2008 1:06 PM > To: 'David Afshartous'; r-help@r-project.org > Subject: Re: [R] Loop avoidance in simulating a vector > > Have a look at mapply. > > -Christos > > > -Original Message- > > From: [EMAIL PROTECTED] > > [mailto:[EMAIL PROTECTED] On Behalf Of David Afshartous > > Sent: Thursday, October 16, 2008 3:47 PM > > To: r-help@r-project.org > > Subject: [R] Loop avoidance in simulating a vector > > > > > > > > All, > > > > I'd like to simulate a vector that is formed from many > > distinct distributions and avoid a loop if possible. E.g, consider: > > > > mu = c(1, 2, 3) > > sigma = c(1, 2, 3) > > n = c(10, 10, 10) > > > > And we simulate a vector of length 30 that consists of > > N(mu[i], sigma[i]) > > distributed data, each of length n[i]. Of course for just > > three groups we > > can simply write it out as: > > > > DV = c(rnorm(n[1], mu[1], sigma[1]), rnorm(n[2], mu[2], > > sigma[2]), rnorm(n[3], mu[3], sigma[3]) ) > > > > For many groups we can use a loop (assuming equal numbers per group): > > > > n = n[1] > > DV = numeric(N*n) > > for (i in 1:N) { > > DV[(n*i - (n-1)): (n*i)] = rnorm(n, mu[i], sigma[i]) > > } > > > > Is there any way to do the general cas without using a loop? > > > > Cheers, > > David > > > > __ > > 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. > > __ > 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] Loop avoidance in simulating a vector
Or you can do it in one line (rnorm is vectorized): DV <- rnorm( sum(n), rep(mu, each=n), rep(sigma, each=n) ) -- Gregory (Greg) L. Snow Ph.D. Statistical Data Center Intermountain Healthcare [EMAIL PROTECTED] 801.408.8111 > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > project.org] On Behalf Of Ray Brownrigg > Sent: Thursday, October 16, 2008 2:36 PM > To: r-help@r-project.org > Cc: 'David Afshartous'; Bert Gunter > Subject: Re: [R] Loop avoidance in simulating a vector > > If you want to avoid using a loop, rather than coding a loop, then > someting like: > > DV <- rnorm(sum(n)) > DV <- DV * rep(sigma, times=n) + rep(mu, times=n) > > will achieve the same as the loop you specified, but generalised to > non-constant n. > > HTH > Ray Brownrigg > > On Fri, 17 Oct 2008, Bert Gunter wrote: > > mapply is still a (disguised) loop (at the interpreted level). So > other > > than improving code readability (always a good thing!), it shouldn't > make > > much of an efficiency difference. > > > > A longer answer is: if all you're doing is a location-scale family of > > distributions, then creating a matrix of standard normal (or > whatever) > > distributed data for all 1:N at once and then using matrix operations > to > > multiply and add, say, so each column becomes your different > distribution > > might be faster. This gets the loops down to C code. > > > > A shorter answer is: it's unlikely that any of this makes enough of a > > difference to be worth the effort. Random number generation is so > efficient > > in R that "avoiding loops" rarely matters. > > > > Also see ?replicate for a way to perhaps write cleaner code (but > still > > using hidden interpreted loops). > > > > -- Bert Gunter > > > > -Original Message- > > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > project.org] On > > Behalf Of Christos Hatzis > > Sent: Thursday, October 16, 2008 1:06 PM > > To: 'David Afshartous'; r-help@r-project.org > > Subject: Re: [R] Loop avoidance in simulating a vector > > > > Have a look at mapply. > > > > -Christos > > > > > -Original Message- > > > From: [EMAIL PROTECTED] > > > [mailto:[EMAIL PROTECTED] On Behalf Of David Afshartous > > > Sent: Thursday, October 16, 2008 3:47 PM > > > To: r-help@r-project.org > > > Subject: [R] Loop avoidance in simulating a vector > > > > > > > > > > > > All, > > > > > > I'd like to simulate a vector that is formed from many > > > distinct distributions and avoid a loop if possible. E.g, > consider: > > > > > > mu = c(1, 2, 3) > > > sigma = c(1, 2, 3) > > > n = c(10, 10, 10) > > > > > > And we simulate a vector of length 30 that consists of > > > N(mu[i], sigma[i]) > > > distributed data, each of length n[i]. Of course for just > > > three groups we > > > can simply write it out as: > > > > > > DV = c(rnorm(n[1], mu[1], sigma[1]), rnorm(n[2], mu[2], > > > sigma[2]), rnorm(n[3], mu[3], sigma[3]) ) > > > > > > For many groups we can use a loop (assuming equal numbers per > group): > > > > > > n = n[1] > > > DV = numeric(N*n) > > > for (i in 1:N) { > > > DV[(n*i - (n-1)): (n*i)] = rnorm(n, mu[i], sigma[i]) > > > } > > > > > > Is there any way to do the general cas without using a loop? > > > > > > Cheers, > > > David > > > > > > __ > > > 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. > > > > __ > > 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. __ 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] Loop for in R to generate several variables
Hi everybody, I have to create several variables of this form: Yind = L0 + L1*X1 + L2*X2 + L3*X3 + K*Cind + n where ind varires in {1,...,10} I thought to this loop for but it does not work: for (ind in 1:10) { Yind = L0 + L1*X1 + L2*X2 + L3*X3 + K*Cind + n } Any suggestions? Thank you. -- View this message in context: http://www.nabble.com/Loop-for-in-R-to-generate-several-variables-tp16536683p16536683.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] Loop to fill in array skips over certain columns
Hello, Below is a simple loop that should place a 3 in the first row of each column in the array "List". iterations<-3 tweaksize<-0.00 ii <-1 List=array(-1000, dim=c(iterations,11)) colnames(List) <- c("orig", "0.05", "0.10", "0.15","0.20","0.25","0.30","0.35","0.40","0.45","0.50") Entry=3 while (tweaksize<=0.5) { if (tweaksize==0.00) coll = 1 if (tweaksize==0.05) coll = 2 if (tweaksize==0.10) coll = 3 if (tweaksize==0.15) coll = 4 if (tweaksize==0.20) coll = 5 if (tweaksize==0.25) coll = 6 if (tweaksize==0.30) coll = 7 if (tweaksize==0.35) coll = 8 if (tweaksize==0.40) coll = 9 if (tweaksize==0.45) coll = 10 if (tweaksize==0.50) coll = 11 List[ii,coll]=Entry tweaksize = tweaksize + 0.05 } List However, if I run the loop, R skips the 4th column (0.15), 9th column (0.40), 10th column (0.45), and eleventh column (0.50). Below is the output: orig 0.05 0.10 0.15 0.20 0.25 0.30 0.35 0.40 0.45 0.50 [1,] 3 3 3 -1000 3 3 3 3 -1000 -1000 -1000 [2,] -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 [3,] -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 Can anyone please suggest a reason why R is skipping these four columns? Any help will be greatly appreciated. Thank you, Paul __ 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] Loop for in R to generate several variables
On Mon, Apr 7, 2008 at 11:31 AM, arpino <[EMAIL PROTECTED]> wrote: > > Hi everybody, > I have to create several variables of this form: > > Yind = L0 + L1*X1 + L2*X2 + L3*X3 + K*Cind + n > > where ind varires in {1,...,10} > > I thought to this loop for but it does not work: > > for (ind in 1:10) { > > Yind = L0 + L1*X1 + L2*X2 + L3*X3 + K*Cind + n > > > } > > Any suggestions? > > Thank you. > > look up ?assign and ?get, i.e: for (ind in 1:10) { assign(paste("Y",ind,sep=""),L0 + L1*X1 + L2*X2 + L3*X3 + get(paste("C",ind,sep=""))+ n) } regards, Gustaf -- Gustaf Rydevik, M.Sci. tel: +46(0)703 051 451 address:Essingetorget 40,112 66 Stockholm, SE skype:gustaf_rydevik __ 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] Loop for in R to generate several variables
Gustaf Rydevik wrote: > On Mon, Apr 7, 2008 at 11:31 AM, arpino <[EMAIL PROTECTED]> wrote: >> Hi everybody, >> I have to create several variables of this form: >> >> Yind = L0 + L1*X1 + L2*X2 + L3*X3 + K*Cind + n >> >> where ind varires in {1,...,10} > > look up ?assign and ?get, i.e: > for (ind in 1:10) { > assign(paste("Y",ind,sep=""),L0 + L1*X1 + L2*X2 + L3*X3 + > get(paste("C",ind,sep=""))+ n) > } EXCEPT you probably don't really want to do that. Much much better to store the results in a list(), so you can access each element in a much more obvious way, with an integer index, unlike that faffing with assign() and get(). Y=list() for(ind in 1:10){ Y[[ind]] = foo(ind) } Then Y[[1]] and so on gives you the values. Barry __ 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] Loop to fill in array skips over certain columns
FAQ 7.31 -- Gregory (Greg) L. Snow Ph.D. Statistical Data Center Intermountain Healthcare [EMAIL PROTECTED] (801) 408-8111 > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED] > Sent: Friday, September 12, 2008 7:36 AM > To: r-help@r-project.org > Subject: [R] Loop to fill in array skips over certain columns > > Hello, > > Below is a simple loop that should place a 3 in the first row > of each column in the array "List". > > iterations<-3 > tweaksize<-0.00 > ii <-1 > List=array(-1000, dim=c(iterations,11)) > colnames(List) <- c("orig", "0.05", "0.10", > "0.15","0.20","0.25","0.30","0.35","0.40","0.45","0.50") > Entry=3 > > while (tweaksize<=0.5) { > if (tweaksize==0.00) coll = 1 > if (tweaksize==0.05) coll = 2 > if (tweaksize==0.10) coll = 3 > if (tweaksize==0.15) coll = 4 > if (tweaksize==0.20) coll = 5 > if (tweaksize==0.25) coll = 6 > if (tweaksize==0.30) coll = 7 > if (tweaksize==0.35) coll = 8 > if (tweaksize==0.40) coll = 9 > if (tweaksize==0.45) coll = 10 > if (tweaksize==0.50) coll = 11 > > List[ii,coll]=Entry > tweaksize = tweaksize + 0.05 > } > > List > > However, if I run the loop, R skips the 4th column (0.15), > 9th column (0.40), 10th column (0.45), and eleventh column > (0.50). Below is the > output: > >orig 0.05 0.10 0.15 0.20 0.25 0.30 0.35 0.40 > 0.45 0.50 > [1,] 3 3 3 -1000 3 3 3 3 -1000 -1000 -1000 > [2,] -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 -1000 > -1000 -1000 [3,] -1000 -1000 -1000 -1000 -1000 -1000 -1000 > -1000 -1000 -1000 -1000 > > Can anyone please suggest a reason why R is skipping these > four columns? Any help will be greatly appreciated. > > Thank you, > > Paul > > __ > 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.
[R] loop? apply? I want to repeat a task through 208 itterations.
structure(list(RM215alk = c(15, 13, 12, 14, NA, 13, 16, 13, 16, #subset of data 13, 17, 13, 19, 13, 14, 14, 15, 15, 14, 16, 14, 15, 13, 14), NSCl = c(NA, NA, 2.9, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("RM215alk", "NSCl"), class = "data.frame", row.names = c(NA, -24L)) apply(if n>=3(x.f, 2, shapiro.test)else(NULL)) #crappy code showing my lack of knowledge on the subject I would like to apply this to a 208 column data matrix, and this is the first time I have tried a repetitive task in R- so please bear with me. the shapiro.test requires 3 to 5000 observations and there are some columns that don't have three observation making it unnecessary to preform a test for normality. How do I do this? thanks stephen -- Let's not spend our time and resources thinking about things that are so little or so large that all they really do for us is puff us up and make us feel like gods. We are mammals, and have not exhausted the annoying little problems of being mammals. -K. Mullis __ 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] loop? apply? I want to repeat a task through 208 itterations.
I think this is what you want to do. I did not have 'shaprio.test' so I just returned a value: > x <- structure(list(RM215alk = c(15, 13, 12, 14, NA, 13, 16, 13, 16, + #subset of data + 13, 17, 13, 19, 13, 14, 14, 15, 15, 14, 16, 14, 15, 13, 14), +NSCl = c(NA, NA, 2.9, NA, NA, NA, NA, NA, NA, NA, NA, NA, +NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("RM215alk", + "NSCl"), class = "data.frame", row.names = c(NA, -24L)) > > apply(x, 2, function(.col){ + if (sum(!is.na(.col)) >= 3) 3 # I don't have this function: shaprio.test(.col) + else NULL + }) $RM215alk [1] 3 $NSCl NULL On Fri, Apr 4, 2008 at 10:44 AM, stephen sefick <[EMAIL PROTECTED]> wrote: > structure(list(RM215alk = c(15, 13, 12, 14, NA, 13, 16, 13, 16, > #subset of data > 13, 17, 13, 19, 13, 14, 14, 15, 15, 14, 16, 14, 15, 13, 14), >NSCl = c(NA, NA, 2.9, NA, NA, NA, NA, NA, NA, NA, NA, NA, >NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("RM215alk", > "NSCl"), class = "data.frame", row.names = c(NA, -24L)) > > apply(if n>=3(x.f, 2, shapiro.test)else(NULL)) #crappy code showing my > lack of knowledge on the subject > > I would like to apply this to a 208 column data matrix, and this is > the first time I have tried a repetitive task in R- so please bear > with me. the shapiro.test requires 3 to 5000 observations and there > are some columns that don't have three observation making it > unnecessary to preform a test for normality. How do I do this? > thanks > > stephen > -- > Let's not spend our time and resources thinking about things that are > so little or so large that all they really do for us is puff us up and > make us feel like gods. We are mammals, and have not exhausted the > annoying little problems of being mammals. > >-K. Mullis > > __ > 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 Cincinnati, OH +1 513 646 9390 What is the problem 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.
Re: [R] loop? apply? I want to repeat a task through 208 itterations.
hi Stephen, you may want to check ?apply What you want is : a<-matrix(1:120,10,20) a[1:8,1:2]=NA apply(a,2, function(x) if(sum(!is.na(x)) > (length(x)-3)) shapiro.test(x) else NA ) Cheers Anna - Messaggio originale - Da: stephen sefick <[EMAIL PROTECTED]> A: r-help@r-project.org Inviato: Venerdì 4 aprile 2008, 8:44:45 Oggetto: [R] loop? apply? I want to repeat a task through 208 itterations. structure(list(RM215alk = c(15, 13, 12, 14, NA, 13, 16, 13, 16, #subset of data 13, 17, 13, 19, 13, 14, 14, 15, 15, 14, 16, 14, 15, 13, 14), NSCl = c(NA, NA, 2.9, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("RM215alk", "NSCl"), class = "data.frame", row.names = c(NA, -24L)) apply(if n>=3(x.f, 2, shapiro.test)else(NULL)) #crappy code showing my lack of knowledge on the subject I would like to apply this to a 208 column data matrix, and this is the first time I have tried a repetitive task in R- so please bear with me. the shapiro.test requires 3 to 5000 observations and there are some columns that don't have three observation making it unnecessary to preform a test for normality. How do I do this? thanks stephen -- Let's not spend our time and resources thinking about things that are so little or so large that all they really do for us is puff us up and make us feel like gods. We are mammals, and have not exhausted the annoying little problems of being mammals. -K. Mullis __ 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. La casella di posta intelligente. [[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.