Re: [R] Plotting a functional time series
Thanks a lot! Regards, Eduardo On Thu, Feb 24, 2011 at 6:47 PM, David Winsemius wrote: > > On Feb 24, 2011, at 3:06 PM, Eduardo de Oliveira Horta wrote: > >> It seems the code I've sent had typos... >> >> Here's a corrected version: >> >> # >> x <- sapply(1:10, function(i)rnorm(1000)) >> f <- sapply(1:10, function(i)density(x[,i], from=-5,to=5)$y) >> grid <- density(x[,1], from=-5,to=5)$x >> win.graph() >> persp(grid, 1:10, f,theta=-50, phi=30, d=2) >> >> win.graph() >> opar <- par(mfrow=c(5,2), mar=c(2,2,1,1)) >> sapply(1:10, function(i)plot(grid, f[,i], ann=FALSE, type="l")) >> par(opar) >> # > > This would put them all on one plot: > > x <- sapply(1:10, function(i)rnorm(1000)) > f <- sapply(1:10, function(i)density(x[,i], from=-5,to=5)$y) > grid <- density(x[,1], from=-5,to=5)$x > pdf() > persp(grid, 1:10, f,theta=-50, phi=30, d=2) > opar <- par(mfrow=c(5,2), mar=c(2,2,1,1)) > pdf() ; plot(grid, f[,1], ann=FALSE, type="l") #only one plot > sapply(2:10, function(i) lines(grid, f[,i])) # the rest with lines() > par(opar); dev.off() > > You could color code them with rainbow colors. There is also a lattice > example with such profiles stacked on top of each other ( in chapter 14 if I > remember correctly) and all the lattice examples are on the web at the book > site. Search on: > > sarkar lattice > >> >> Sorry for the mistake. >> >> Best regards, >> >> Eduardo >> >> On Mon, Feb 21, 2011 at 11:18 PM, Eduardo de Oliveira Horta >> wrote: >>> >>> Hello, >>> >>> I'm willing to plot a sequence of densities on a 3d graph, something like >>> >>> - >>> x <- sapply(1:10, function(i)rnorm(1000)) >>> >>> f <- sapply(1:10, function(i)density(x[,i], from=-5,to=5)$y) >>> grid <- density(x[,1], from=-5,to=5)$x >>> >>> win.graph() >>> persp(grid1, 1:10, f,theta=-50, phi=30, d=2) >>> - >>> >>> That is, I simply want to stack the curves >>> >>> - >>> win.graph() >>> opar <- par(mfrow=c(5,2), mar=c(2,2,1,1)) >>> sapply(1:10, function(i)plot(grid, f[,i], ann=FALSE, type="l")) >>> par(opar) >>> - >>> >>> into a functional time series plot (unlike the example above, I'm >>> working with pdf's which are not independent). >>> >>> The result I get using persp() is 'almost' what I want, but I would >>> like to avoid the wireframes connecting the densities along 1:10, >>> because there's no continuity in that direction. In other words, I >>> wanted that the only lines appearing in the plot to be those >>> corresponding to the pdf's f[,1],...f[,10]. >>> >>> Thanks once again, and best regards, >>> >>> Eduardo >>> >>>> sessionInfo() >>> >>> R version 2.11.1 (2010-05-31) >>> i386-pc-mingw32 >>> >>> locale: >>> [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 >>> [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C >>> [5] LC_TIME=Portuguese_Brazil.1252 >>> >>> attached base packages: >>> [1] stats graphics grDevices utils datasets methods base >>> >>> other attached packages: >>> [1] rgl_0.92.798 Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 >>> >>> loaded via a namespace (and not attached): >>> [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 >>> [5] XML_3.1-0 >>> >>> __ >>> 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. > > David Winsemius, MD > West Hartford, CT > > __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Plotting a functional time series
It seems the code I've sent had typos... Here's a corrected version: # x <- sapply(1:10, function(i)rnorm(1000)) f <- sapply(1:10, function(i)density(x[,i], from=-5,to=5)$y) grid <- density(x[,1], from=-5,to=5)$x win.graph() persp(grid, 1:10, f,theta=-50, phi=30, d=2) win.graph() opar <- par(mfrow=c(5,2), mar=c(2,2,1,1)) sapply(1:10, function(i)plot(grid, f[,i], ann=FALSE, type="l")) par(opar) # Sorry for the mistake. Best regards, Eduardo On Mon, Feb 21, 2011 at 11:18 PM, Eduardo de Oliveira Horta wrote: > Hello, > > I'm willing to plot a sequence of densities on a 3d graph, something like > > - > x <- sapply(1:10, function(i)rnorm(1000)) > > f <- sapply(1:10, function(i)density(x[,i], from=-5,to=5)$y) > grid <- density(x[,1], from=-5,to=5)$x > > win.graph() > persp(grid1, 1:10, f,theta=-50, phi=30, d=2) > - > > That is, I simply want to stack the curves > > - > win.graph() > opar <- par(mfrow=c(5,2), mar=c(2,2,1,1)) > sapply(1:10, function(i)plot(grid, f[,i], ann=FALSE, type="l")) > par(opar) > - > > into a functional time series plot (unlike the example above, I'm > working with pdf's which are not independent). > > The result I get using persp() is 'almost' what I want, but I would > like to avoid the wireframes connecting the densities along 1:10, > because there's no continuity in that direction. In other words, I > wanted that the only lines appearing in the plot to be those > corresponding to the pdf's f[,1],...f[,10]. > > Thanks once again, and best regards, > > Eduardo > >> sessionInfo() > R version 2.11.1 (2010-05-31) > i386-pc-mingw32 > > locale: > [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 > [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C > [5] LC_TIME=Portuguese_Brazil.1252 > > attached base packages: > [1] stats graphics grDevices utils datasets methods base > > other attached packages: > [1] rgl_0.92.798 Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 > > loaded via a namespace (and not attached): > [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 > [5] XML_3.1-0 > > __ > 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] Plotting a functional time series
Hello, I'm willing to plot a sequence of densities on a 3d graph, something like - x <- sapply(1:10, function(i)rnorm(1000)) f <- sapply(1:10, function(i)density(x[,i], from=-5,to=5)$y) grid <- density(x[,1], from=-5,to=5)$x win.graph() persp(grid1, 1:10, f,theta=-50, phi=30, d=2) - That is, I simply want to stack the curves - win.graph() opar <- par(mfrow=c(5,2), mar=c(2,2,1,1)) sapply(1:10, function(i)plot(grid, f[,i], ann=FALSE, type="l")) par(opar) - into a functional time series plot (unlike the example above, I'm working with pdf's which are not independent). The result I get using persp() is 'almost' what I want, but I would like to avoid the wireframes connecting the densities along 1:10, because there's no continuity in that direction. In other words, I wanted that the only lines appearing in the plot to be those corresponding to the pdf's f[,1],...f[,10]. Thanks once again, and best regards, Eduardo > sessionInfo() R version 2.11.1 (2010-05-31) i386-pc-mingw32 locale: [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C [5] LC_TIME=Portuguese_Brazil.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] rgl_0.92.798 Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 loaded via a namespace (and not attached): [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 [5] XML_3.1-0 __ 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] Building an array from matrix blocks
Thanks! On Mon, Feb 21, 2011 at 11:40 AM, wrote: > Well, you can lose B by just adding to X in the first for-loop, can't you? > For (...) X <- X + A[...] > > But if you want elegance, you could try: > > X = Reduce("+",lapply(1:(p+1), function(i) A[i:(n-p-1+i),i:(n-p-1+i)])) > > I imagine someone can be even more eleganter than this. > > rad > > -Original Message- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf Of Eduardo de Oliveira Horta > Sent: Saturday, February 19, 2011 9:49 AM > To: r-help > Subject: [R] Building an array from matrix blocks > > Hello, > > I've googled for a while and couldn't find anything on this topic: say > I have a matrix A and want to build matrices B1, B2,... using blocks > from A (or equivalently an array B with B[,,i] being a block from A), > and that I must sum the B[,,i]'s. > > I've come up with this rather non-elegant code: > >> n = 6 >> p = 3 >> >> A <- matrix(1:(n^2), n, n, byrow=TRUE) >> >> B <- array(0, c(n-p, n-p, p+1)) >> for (i in 1:(p+1)) B[,,i] <- A[i:(n-p-1+i), i:(n-p-1+i)] >> >> X <- matrix(0, n-p, n-p) >> for (i in 1:(p+1)) X <- X + B[,,i] >> A > [,1] [,2] [,3] [,4] [,5] [,6] > [1,] 1 2 3 4 5 6 > [2,] 7 8 9 10 11 12 > [3,] 13 14 15 16 17 18 > [4,] 19 20 21 22 23 24 > [5,] 25 26 27 28 29 30 > [6,] 31 32 33 34 35 36 >> B > , , 1 > > [,1] [,2] [,3] > [1,] 1 2 3 > [2,] 7 8 9 > [3,] 13 14 15 > > , , 2 > > [,1] [,2] [,3] > [1,] 8 9 10 > [2,] 14 15 16 > [3,] 20 21 22 > > , , 3 > > [,1] [,2] [,3] > [1,] 15 16 17 > [2,] 21 22 23 > [3,] 27 28 29 > > , , 4 > > [,1] [,2] [,3] > [1,] 22 23 24 > [2,] 28 29 30 > [3,] 34 35 36 > >> X > [,1] [,2] [,3] > [1,] 46 50 54 > [2,] 70 74 78 > [3,] 94 98 102 > > Note that the blocks B[,,i] are obtained by sweeping the diagonal of > A. I wonder if there is a better and faster way to achieve this using > block matrix operations for instance. Actually what matters most for > me is getting to the matrix X, so if it is possible to do this without > having to construct the array B it would be ok as well... > > Interesting observation: > >> system.time(for (j in 1:1) {X <- matrix(0, n-p, n-p); for (i in 1:(p+1)) >> X <- X + B[,,i]}) > user system elapsed > 0.27 0.00 0.26 >> system.time(for (j in 1:1) {X <- apply(B,c(1,2),sum)}) > user system elapsed > 1.82 0.02 1.86 > > Thanks in advance, and best regards, > > Eduardo Horta > >> sessionInfo() > R version 2.11.1 (2010-05-31) > x86_64-pc-mingw32 > > locale: > [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 > [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C > [5] LC_TIME=Portuguese_Brazil.1252 > > attached base packages: > [1] stats graphics grDevices utils datasets methods base > > other attached packages: > [1] Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 > > loaded via a namespace (and not attached): > [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 > [5] XML_3.1-0 > > __ > 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. > > > > > message may contain confidential information. If you are not the designated > recipient, please notify the sender immediately, and delete the original and > any copies. Any use of the message by you is prohibited. > > __ 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] Building an array from matrix blocks
Hello, I've googled for a while and couldn't find anything on this topic: say I have a matrix A and want to build matrices B1, B2,... using blocks from A (or equivalently an array B with B[,,i] being a block from A), and that I must sum the B[,,i]'s. I've come up with this rather non-elegant code: > n = 6 > p = 3 > > A <- matrix(1:(n^2), n, n, byrow=TRUE) > > B <- array(0, c(n-p, n-p, p+1)) > for (i in 1:(p+1)) B[,,i] <- A[i:(n-p-1+i), i:(n-p-1+i)] > > X <- matrix(0, n-p, n-p) > for (i in 1:(p+1)) X <- X + B[,,i] > A [,1] [,2] [,3] [,4] [,5] [,6] [1,]123456 [2,]789 10 11 12 [3,] 13 14 15 16 17 18 [4,] 19 20 21 22 23 24 [5,] 25 26 27 28 29 30 [6,] 31 32 33 34 35 36 > B , , 1 [,1] [,2] [,3] [1,]123 [2,]789 [3,] 13 14 15 , , 2 [,1] [,2] [,3] [1,]89 10 [2,] 14 15 16 [3,] 20 21 22 , , 3 [,1] [,2] [,3] [1,] 15 16 17 [2,] 21 22 23 [3,] 27 28 29 , , 4 [,1] [,2] [,3] [1,] 22 23 24 [2,] 28 29 30 [3,] 34 35 36 > X [,1] [,2] [,3] [1,] 46 50 54 [2,] 70 74 78 [3,] 94 98 102 Note that the blocks B[,,i] are obtained by sweeping the diagonal of A. I wonder if there is a better and faster way to achieve this using block matrix operations for instance. Actually what matters most for me is getting to the matrix X, so if it is possible to do this without having to construct the array B it would be ok as well... Interesting observation: > system.time(for (j in 1:1) {X <- matrix(0, n-p, n-p); for (i in 1:(p+1)) > X <- X + B[,,i]}) user system elapsed 0.270.000.26 > system.time(for (j in 1:1) {X <- apply(B,c(1,2),sum)}) user system elapsed 1.820.021.86 Thanks in advance, and best regards, Eduardo Horta > sessionInfo() R version 2.11.1 (2010-05-31) x86_64-pc-mingw32 locale: [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C [5] LC_TIME=Portuguese_Brazil.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 loaded via a namespace (and not attached): [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 [5] XML_3.1-0 __ 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] Defining functions inside loops
Yes, that was it. Thanks a lot. Best regards, Eduardo On Tue, Feb 15, 2011 at 2:34 PM, jim holtman wrote: > The try this: > >> s <- c( 0.2, 0.45, 0.38, 0.9) >> f <- lapply(1:10, function(i) > + local({ > + local_s <- s[i] > + function(x)x^2+local_s > + })) >> rm(s) >> f[[2]](4) > [1] 16.45 >> > > > > On Tue, Feb 15, 2011 at 10:53 AM, Eduardo de Oliveira Horta > wrote: >> Thanks... but I guess I didn't make myself clear. What I was trying to >> do was precisely to "store" inside the function the number associated >> to s[i] rather than the call to s[i], such that I wouldn't need to >> keep that object in subsequent function calls. >> >> In other words, I wanted to use lapply to get functions equivalent to: >> s <- c( 0.2, 0.45, 0.38, 0.9) >> f <-list() >> f[[1]] <- function(x) x^2+0.2 >> f[[2]] <- function(x) x^2+0.45 >> f[[3]] <- function(x) x^2+0.38 >> f[[4]] <- function(x) x^2+0.9 >> >> Best regards, >> >> Eduardo >> >> >> On Tue, Feb 15, 2011 at 7:20 AM, Dennis Murphy wrote: >>> Hi: >>> >>> If you look at the error message, you'll see that you removed s before >>> evaluating f, and since an element of s is called in the function >>> >>> Try >>>> s <- c( 0.2, 0.45, 0.38, 0.9) >>>> f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+s[i]})) >>>> f[[1]](s) >>> [1] 0.2400 0.4025 0.3444 1.0100 >>> >>> f is a list with 10 components, the first of which is >>> [[1]] >>> function (x) >>> x^2 + s[i] >>> >>> >>> Each component occupies a different environment. To see what you get, >>> >>>> f[[1]](0.1) >>> [1] 0.21 >>> >>>> for(i in 1:10) print(f[[i]](i)) >>> [1] 1.2 >>> [1] 4.45 >>> [1] 9.38 >>> [1] 16.9 >>> [1] NA >>> [1] NA >>> [1] NA >>> [1] NA >>> [1] NA >>> [1] NA >>> >>>> for(i in 1:10) print(f[[i]](1)) >>> [1] 1.2 >>> [1] 1.45 >>> [1] 1.38 >>> [1] 1.9 >>> [1] NA >>> [1] NA >>> [1] NA >>> [1] NA >>> [1] NA >>> [1] NA >>> >>> HTH, >>> Dennis >>> >>> On Mon, Feb 14, 2011 at 9:50 PM, Eduardo de Oliveira Horta >>> wrote: >>>> >>>> Hello again. >>>> >>>> Let me try something a little more intricate. Let's say instead of >>>> forcing evaluation of 'i' I'd want to force evaluation of a vector; >>>> for example: >>>> s <- c( 0.2, 0.45, 0.38, 0.9) >>>> f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+s[i]})) >>>> rm(s) >>>> f[[1]](0.1) >>>> Error in f[[1]](0.1) : object 's' not found >>>> >>>> Any thoughts? >>>> >>>> Best regards, >>>> >>>> Eduardo >>>> >>>> > sessionInfo() >>>> R version 2.11.1 (2010-05-31) >>>> x86_64-pc-mingw32 >>>> >>>> locale: >>>> [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 >>>> [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C >>>> [5] LC_TIME=Portuguese_Brazil.1252 >>>> >>>> attached base packages: >>>> [1] stats graphics grDevices utils datasets methods base >>>> >>>> other attached packages: >>>> [1] Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 >>>> >>>> loaded via a namespace (and not attached): >>>> [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 >>>> [5] XML_3.1-0 >>>> >>>> > On Mon, Nov 15, 2010 at 7:10 PM, William Dunlap >>>> > wrote: >>>> >> You could make f[[i]] be function(t)t^2+i for i in 1:10 >>>> >> with >>>> >> f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+i})) >>>> >> After that we get the correct results >>>> >> > f[[7]](100:103) >>>> >> [1] 10007 10208 10411 10616 >>>> >> but looking at the function doesn't immdiately tell you >>>> >> what 'i' is in the function >>>> >> > f[[7]] >>>> >> fu
Re: [R] Defining functions inside loops
Thanks... but I guess I didn't make myself clear. What I was trying to do was precisely to "store" inside the function the number associated to s[i] rather than the call to s[i], such that I wouldn't need to keep that object in subsequent function calls. In other words, I wanted to use lapply to get functions equivalent to: s <- c( 0.2, 0.45, 0.38, 0.9) f <-list() f[[1]] <- function(x) x^2+0.2 f[[2]] <- function(x) x^2+0.45 f[[3]] <- function(x) x^2+0.38 f[[4]] <- function(x) x^2+0.9 Best regards, Eduardo On Tue, Feb 15, 2011 at 7:20 AM, Dennis Murphy wrote: > Hi: > > If you look at the error message, you'll see that you removed s before > evaluating f, and since an element of s is called in the function > > Try >> s <- c( 0.2, 0.45, 0.38, 0.9) >> f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+s[i]})) >> f[[1]](s) > [1] 0.2400 0.4025 0.3444 1.0100 > > f is a list with 10 components, the first of which is > [[1]] > function (x) > x^2 + s[i] > > > Each component occupies a different environment. To see what you get, > >> f[[1]](0.1) > [1] 0.21 > >> for(i in 1:10) print(f[[i]](i)) > [1] 1.2 > [1] 4.45 > [1] 9.38 > [1] 16.9 > [1] NA > [1] NA > [1] NA > [1] NA > [1] NA > [1] NA > >> for(i in 1:10) print(f[[i]](1)) > [1] 1.2 > [1] 1.45 > [1] 1.38 > [1] 1.9 > [1] NA > [1] NA > [1] NA > [1] NA > [1] NA > [1] NA > > HTH, > Dennis > > On Mon, Feb 14, 2011 at 9:50 PM, Eduardo de Oliveira Horta > wrote: >> >> Hello again. >> >> Let me try something a little more intricate. Let's say instead of >> forcing evaluation of 'i' I'd want to force evaluation of a vector; >> for example: >> s <- c( 0.2, 0.45, 0.38, 0.9) >> f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+s[i]})) >> rm(s) >> f[[1]](0.1) >> Error in f[[1]](0.1) : object 's' not found >> >> Any thoughts? >> >> Best regards, >> >> Eduardo >> >> > sessionInfo() >> R version 2.11.1 (2010-05-31) >> x86_64-pc-mingw32 >> >> locale: >> [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 >> [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C >> [5] LC_TIME=Portuguese_Brazil.1252 >> >> attached base packages: >> [1] stats graphics grDevices utils datasets methods base >> >> other attached packages: >> [1] Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 >> >> loaded via a namespace (and not attached): >> [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 >> [5] XML_3.1-0 >> >> > On Mon, Nov 15, 2010 at 7:10 PM, William Dunlap >> > wrote: >> >> You could make f[[i]] be function(t)t^2+i for i in 1:10 >> >> with >> >> f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+i})) >> >> After that we get the correct results >> >> > f[[7]](100:103) >> >> [1] 10007 10208 10411 10616 >> >> but looking at the function doesn't immdiately tell you >> >> what 'i' is in the function >> >> > f[[7]] >> >> function (x) >> >> x^2 + i >> >> >> >> You can find it in f[[7]]'s environment >> >> > get("i", envir=environment(f[[7]])) >> >> [1] 7 >> >> >> >> The call to force() in the call to local() is not >> >> necessary in this case, although it can help in >> >> other situations. >> >> >> >> Bill Dunlap >> >> Spotfire, TIBCO Software >> >> wdunlap tibco.com >> >> >> >>> -Original Message- >> >>> From: r-help-boun...@r-project.org >> >>> [mailto:r-help-boun...@r-project.org] On Behalf Of Eduardo de >> >>> Oliveira Horta >> >>> Sent: Monday, November 15, 2010 12:50 PM >> >>> To: r-help@r-project.org >> >>> Subject: [R] Defining functions inside loops >> >>> >> >>> Hello, >> >>> >> >>> I was trying to define a set of functions inside a loop, with >> >>> the loop index >> >>> working as a parameter for each function. Below I post a >> >>> simpler example, as >> >>> to illustrate what I was intending: >> >>> >> >>> f<-list() >> >>> for (i in 1:10){ >> >>> f[[i
Re: [R] Defining functions inside loops
Hello again. Let me try something a little more intricate. Let's say instead of forcing evaluation of 'i' I'd want to force evaluation of a vector; for example: s <- c( 0.2, 0.45, 0.38, 0.9) f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+s[i]})) rm(s) f[[1]](0.1) Error in f[[1]](0.1) : object 's' not found Any thoughts? Best regards, Eduardo > sessionInfo() R version 2.11.1 (2010-05-31) x86_64-pc-mingw32 locale: [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C [5] LC_TIME=Portuguese_Brazil.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] Revobase_4.2.0 RevoScaleR_1.1-1 lattice_0.19-13 loaded via a namespace (and not attached): [1] grid_2.11.1 pkgXMLBuilder_1.0 revoIpe_1.0 tools_2.11.1 [5] XML_3.1-0 > On Mon, Nov 15, 2010 at 7:10 PM, William Dunlap wrote: >> You could make f[[i]] be function(t)t^2+i for i in 1:10 >> with >> f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+i})) >> After that we get the correct results >> > f[[7]](100:103) >> [1] 10007 10208 10411 10616 >> but looking at the function doesn't immdiately tell you >> what 'i' is in the function >> > f[[7]] >> function (x) >> x^2 + i >> >> You can find it in f[[7]]'s environment >> > get("i", envir=environment(f[[7]])) >> [1] 7 >> >> The call to force() in the call to local() is not >> necessary in this case, although it can help in >> other situations. >> >> Bill Dunlap >> Spotfire, TIBCO Software >> wdunlap tibco.com >> >>> -Original Message- >>> From: r-help-boun...@r-project.org >>> [mailto:r-help-boun...@r-project.org] On Behalf Of Eduardo de >>> Oliveira Horta >>> Sent: Monday, November 15, 2010 12:50 PM >>> To: r-help@r-project.org >>> Subject: [R] Defining functions inside loops >>> >>> Hello, >>> >>> I was trying to define a set of functions inside a loop, with >>> the loop index >>> working as a parameter for each function. Below I post a >>> simpler example, as >>> to illustrate what I was intending: >>> >>> f<-list() >>> for (i in 1:10){ >>> f[[i]]<-function(t){ >>> f[[i]]<-t^2+i >>> } >>> } >>> rm(i) >>> >>> With that, I was expecting that f[[1]] would be a function >>> defined by t^2+1, >>> f[[2]] by t^2+2 and so on. However, the index i somehow >>> doesn't "get in" the >>> function definition on each loop, that is, the functions >>> f[[1]] through >>> f[[10]] are all defined by t^2+i. Thus, if I remove the >>> object i from the >>> workspace, I get an error when evaluating these functions. >>> Otherwise, if >>> don't remove the object i, it ends the loop with value equal >>> to 10 and then >>> f[[1]](t)=f[[2]](t)=...=f[[10]](t)=t^2+10. >>> >>> I am aware that I could simply put >>> >>> f<-function(u,i){ >>> f<-t^2+i >>> } >>> >>> but that's really not what I want. >>> >>> Any help would be appreciated. Thanks in advance, >>> >>> Eduardo Horta >>> >>> [[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] Average of several line plots
It is not clear from your message whether these data represent functions or such. Could you perhaps bring up an example? I'm guessing each data set contains evaluation points and function values at those points, and that you would like to plot these functions and the mean function all on the same graph, is that right? If the points in the domain differ from each other, it's not as immediate to build a mean function. A quick recipe would be to use splinefun on each data set, generate a new grid for the domain, evaluate each obtained spline on this grid to get new data sets and build the mean function from there. But without an example it's really just guessing. Hope this helps anyway. ?splinefun Best regards, Eduardo On Wed, Feb 2, 2011 at 2:44 PM, mattnixon wrote: > > Hi, > > I have several data sets which are all approximately within the same values > as each other (both X and Y) and all of these data sets more or less overlap > each other when plotted on the same graph. However, although each data set > varies between approximately the same range, there are vastly different > numbers of data points within each data set (due to the nature of how these > values had to be measured). > > Currently, I am trying to figure out a way to produce a graph showing all > these data sets and a line showing the average of all of the data sets. > Given the different number of data points, I can't think of an easy way to > do this. > > Can anybody help? > > Thanks! > -- > View this message in context: > http://r.789695.n4.nabble.com/Average-of-several-line-plots-tp3254850p3254850.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] R-/Text-editor for Windows?
I'm testing StatET right now. Seems nice. In many aspects it resembles the features offered by RKWard (which is a KDE application and thus also platform independent... in principle. No pre-compiled OSX version yet). For those interested, I found an explanation on how to set StatET running. Might be helpful, so here it goes: http://lukemiller.org/index.php/2010/04/eclipse-and-statet-a-nice-working-environment-for-r/ Best regards, Eduardo On Sun, Jan 30, 2011 at 12:19 PM, jthetzel wrote: > > Sascha, > > I second Tobias' recommendation of Eclipse with StatET. Like Emacs, Eclipse > is platform independent and easily extensible to essentially any other > language, as well as revision control like git and svn. I used to use > Tinn-R, but haven't been back seen switching to Eclipse. > > Jeremy > > Jeremy Hetzel > Boston University > -- > View this message in context: > http://r.789695.n4.nabble.com/R-Text-editor-for-Windows-tp3245162p3247173.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] R-/Text-editor for Windows?
Sascha, I guess the software you wan't is RKWard: http://rkward.sourceforge.net/ I have tested a few R front-ends and to me this one seemed the most adequate. I suppose as an ex-matlab user my interface preferences are biased, but still RKWard has a good editor with syntax highlighting, code folding, auto-completion and function hinting, and since it also incorporates the R console into it's structure, anything you type in the console window will be highlighted and hinted (if a function) as well. And it's free. I've tried Emacs Speaks Statistics and found it just confusing, to say the least (by the way, I'm puzzled by why so many people adhere to this one. Maybe it's a matter of getting used to it...?). Tinn-R (up to the version I tested) didn't integrate well with R. WinEDT is good. Give it a try and tell us what you think. Best regards, Eduardo Horta On Fri, Jan 28, 2011 at 4:55 PM, Sascha Vieweg wrote: > Tinn-R (http://www.sciviews.org/Tinn-R/) is one of the topmost suggestions > when googling an R-(text-)editor for Windows. However, to me it appears > dissappointing that Tinn-R does not handle utf-8 (mac-roman, or any other) > encoded R-scripts or, in general, text files. Besides Emacs and the R > built-in editor, could you recommend a good editor for Windows, even some > commmercial for a small price? (For a comparison, TextMate for OS X is 35 > USD and does a great job on all plain text and code related issues, not only > R.) Thanks, *S* > > -- > Sascha Vieweg, saschav...@gmail.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.
[R] pdf greek letter typos
Hi there, yet on the topic of greek letters and pdf plotting: when I run the following code pdf(file="temp.pdf") mu=seq(from=-pi, to=pi, length=100) plot(mu, sin(mu^2), type="l", xlab=expression(mu%in%(list(-pi,pi))), ylab=expression(sin(mu^2)), main=expression((list(mu,sin(mu^2) dev.off() I get a "proportional to" symbol in place of a "mu" and a "not equal to" in place of a "pi" (see attached file). If I run only mu=seq(from=-pi, to=pi, length=100) plot(mu, sin(mu^2), type="l", xlab=expression(mu%in%(list(-pi,pi))), ylab=expression(sin(mu^2)), main=expression((list(mu,sin(mu^2) then the characters are displayed correctly. I would like to know if there is any sort of fixes to this problem, such as specifying the symbols font or embedding fonts into the pdf file. Any help would be welcome. Thanks in advance and best regards, Eduardo Horta temp.pdf Description: Adobe PDF document __ 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] Greek letters in CairoPDF
Hello there, Straight to the point: it seems that CairoPDF from package "Cairo" cannot handle greek letters from expression(). For example, > eta = seq(from=-pi, to=pi, length=100) > f = sin(eta)^2 > pdf(file = "temp_pdf.pdf") > plot(eta, f, type="l", main=expression(f(eta)==sin(eta)^2), > xlab=expression(eta), ylab=expression(f(eta))) > dev.off() gives the expected result, but > require("Cairo") > CairoPDF(file = "temp_CairoPDF.pdf") > plot(eta, f, type="l", main=expression(f(eta)==sin(eta)^2), > xlab=expression(eta), ylab=expression(f(eta))) > dev.off() leaves a blank where it should display the etas. Any ideas here? (session info below) Thanks in advance and best regards, Eduardo > sessionInfo() R version 2.11.1 (2010-05-31) i386-pc-mingw32 locale: [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C [5] LC_TIME=Portuguese_Brazil.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] Cairo_1.4-5 __ 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] Alphabetic labels on multi-plot graphics
Thanks, I wasn't even aware that 'letters' was there. Best regards On Tue, Jan 11, 2011 at 6:08 PM, David Winsemius wrote: > > On Jan 11, 2011, at 2:06 PM, Eduardo de Oliveira Horta wrote: > >> Is there a way to achieve >> >> lbl=c("a", "b", "c", "d") >> >> opar <- par(mfrow=c(2,2), ann=FALSE) >> for (t in 1:4){ >> plot(seq(from=1,to=2*pi,length=100), >> sin(t*seq(from=1,to=2*pi,length=100)), type="l") >> title(main=paste("(", lbl[t], ")", sep="")) >> } >> par(opar) > > opar <- par(mfrow=c(2,2), ann=FALSE) > for (t in 1:4){ > plot(seq(from=1,to=2*pi,length=100), > sin(t*seq(from=1,to=2*pi,length=100)), type="l") > title(main=bquote("("*.(letters[t])*")") ) > } > par(opar) > >> without having to use an object like 'lbl'? > > (You obviously need something from which to construct the titles.) > >> >> More generally: is it possible to iteratively (as in a loop) add >> alphabetic titles to multi-plot graphics when the range over which 't' >> above varies is of an arbitrary length? It is important that >> ann=FALSE, because I don't want the axes labels. >> >> Thanks in advance, and best regards. >> >> Eduardo Horta >> >> __ > > David Winsemius, MD > West Hartford, CT > > __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Alphabetic labels on multi-plot graphics
Is there a way to achieve lbl=c("a", "b", "c", "d") par(mfrow=c(2,2), ann=FALSE) for (t in 1:4){ plot(seq(from=1,to=2*pi,length=100), sin(t*seq(from=1,to=2*pi,length=100)), type="l") title(main=paste("(", lbl[t], ")", sep="")) } without having to use an object like 'lbl'? More generally: is it possible to iteratively (as in a loop) add alphabetic titles to multi-plot graphics when the range over which 't' above varies is of an arbitrary length? It is important that ann=FALSE, because I don't want the axes labels. Thanks in advance, and best regards. Eduardo Horta __ 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] Cairo pdf canvas size
Thanks! On Thu, Jan 6, 2011 at 7:13 PM, Dennis Murphy wrote: > Hi: > > On Thu, Jan 6, 2011 at 5:36 AM, Eduardo de Oliveira Horta > wrote: >> >> Peter, >> thank you, that's what I was looking for! >> David, I forgot to tell you my OS. Sorry... it's Win7. I'm running a >> RKWard session. >> And this is strange: >> > Cairo("example.pdf", type="pdf",width=12,height=12,units="cm",dpi=300) >> Error: could not find function "Cairo" >> ... maybe you're not using the Cairo >> package? http://cran.r-project.org/web/packages/Cairo/Cairo.pdf >> >> And Dennis, thanks for the code. It worked, and I'm considering to adopt >> data frames in the near future. By the way, I'm working with functional time >> series, so each observation is a function (or a vector representing that >> function evaluated on a grid) indexed by time. Any insights on how to >> implement data frames here? > > I don't see a real issue. It would be easier to give you concrete > information if there were an artificial example that mimics your situation, > but it's not that hard. I'd suggest looking into the zoo package to create > a series - it can handle both regular (zooreg()) and irregular (zoo()) > series. Basically, a zoo object is a numeric vector with a time index. One > can create multiple series with a single index, individual series with > different indices that can be combined into data frames, etc. I've browsed > through some of the code that accompanies Ramsey, Hooker and Graves' FDA > book in R and Matlab, and occasionally they use the zoo package as well. > > Here's an example, but I expect that someone will show how to convert the > zoo series to data frames much more efficiently for use in ggplot2... > > library(zoo) > library(ggplot2) > library(lattice) > # Generate three daily series with different start times and lengths > a <- zoo(rnorm(450), as.Date("2005-01-01") + 0:449) > b <- zoo(rnorm(600, 1, 2), as.Date('2005-06-01') + 0:599) > d <- zoo(rnorm(300, 2, 1), as.Date('2004-09-01') + 0:299) > > # Convert to data frame, make time index a variable and make sure it's a > Date object > A <- as.data.frame(a) > B <- as.data.frame(b) > D <- as.data.frame(d) > A$Date <- as.Date(rownames(A)) > B$Date <- as.Date(rownames(B)) > D$Date <- as.Date(rownames(D)) > # Give all three series the same name > names(A)[1] <- names(B)[1] <- names(D)[1] <- 'y' > # Stack the three data frames and create a series ID variable > comb <- rbind(A, B, D) > comb$Series <- rep(c('A', 'B', 'D'), c(nrow(A), nrow(B), nrow(D))) > str(comb) # make sure that Date is a Date object > > # ggplot of the three series > ggplot(comb, aes(x = Date, y = y, color = Series)) + geom_path() > # Stacked individual plots (faceted) > last_plot() + facet_grid(Series ~ .) > > # lattice version > xyplot(y ~ Date, data = comb, groups = Series, type = 'l', col.line = 1:3) > # Stacked individual series > xyplot(y ~ Date | Series, data = comb, type = 'l', layout = c(1, 3)) > > If you need the grid coordinates, use expand.grid() - it can be used when > creating a data frame, too. > > As Bert noted the other night in another thread, one can use xyplot directly > on zoo objects, but I don't have any direct experience with that yet so will > defer to others if they wish to contribute. ?xyplot.zoo provides some > examples. > > Hope this gives you some idea of what can be done, > Dennis > >> Best regards, >> Eduardo >> On Thu, Jan 6, 2011 at 1:47 AM, Peter Langfelder >> wrote: >>> >>> On Wed, Jan 5, 2011 at 7:35 PM, Eduardo de Oliveira Horta >>> wrote: >>> > Something like this: >>> > >>> > u=seq(from=-pi, to=pi, length=1000) >>> > f=sin(u) >>> > Cairo("example.pdf", type="pdf",width=12,height=12,units="cm",dpi=300) >>> > par(cex.axis=.6,col.axis="grey",ann=FALSE, lwd=.25,bty="n", las=1, >>> > tcl=-.2, >>> > mgp=c(3,.5,0)) >>> > xlim=c(-pi,pi) >>> > ylim=round(c(min(f),max(f))) >>> > plot(u,f,xlim,ylim,type="l",col="firebrick3", axes=FALSE) >>> > axis(side=1, lwd=.25, col="darkgrey", at=seq(from=xlim[1], to=xlim[2], >>> > length=5)) >>> > axis(side=2, lwd=.25, col="darkgrey", at=seq(from=ylim[1], to=ylim[2], >>> > length=5)) >>> >
Re: [R] Cairo pdf canvas size
Peter, thank you, that's what I was looking for! David, I forgot to tell you my OS. Sorry... it's Win7. I'm running a RKWard session. And this is strange: > Cairo("example.pdf", type="pdf",width=12,height=12,units="cm",dpi=300) Error: could not find function "Cairo" ... maybe you're not using the Cairo package? http://cran.r-project.org/web/packages/Cairo/Cairo.pdf And Dennis, thanks for the code. It worked, and I'm considering to adopt data frames in the near future. By the way, I'm working with functional time series, so each observation is a function (or a vector representing that function evaluated on a grid) indexed by time. Any insights on how to implement data frames here? Best regards, Eduardo On Thu, Jan 6, 2011 at 1:47 AM, Peter Langfelder wrote: > On Wed, Jan 5, 2011 at 7:35 PM, Eduardo de Oliveira Horta > wrote: > > Something like this: > > > > u=seq(from=-pi, to=pi, length=1000) > > f=sin(u) > > Cairo("example.pdf", type="pdf",width=12,height=12,units="cm",dpi=300) > > par(cex.axis=.6,col.axis="grey",ann=FALSE, lwd=.25,bty="n", las=1, > tcl=-.2, > > mgp=c(3,.5,0)) > > xlim=c(-pi,pi) > > ylim=round(c(min(f),max(f))) > > plot(u,f,xlim,ylim,type="l",col="firebrick3", axes=FALSE) > > axis(side=1, lwd=.25, col="darkgrey", at=seq(from=xlim[1], to=xlim[2], > > length=5)) > > axis(side=2, lwd=.25, col="darkgrey", at=seq(from=ylim[1], to=ylim[2], > > length=5)) > > abline(v=seq(from=xlim[1], to=xlim[2], length=5), lwd=.25,lty="dotted", > > col="grey") > > abline(h=seq(from=ylim[1], to=ylim[2], length=5), lwd=.25,lty="dotted", > > col="grey") > > dev.off() > > > > > > > Wow, you must like light colors :) > > To the point, just set margins, for example > > par(mar = c(2,2,0.5, 0.5)) > > (margins are bottom, left, top, right) > > after the Cairo command. > > BTW, Cairo doesn't work for me either... but I tried your example by > plotting to the screen. > > Peter > > > > > Notice how the canvas' margins are relatively far from the plotting area. > > > > Thanks, > > > > Eduardo > > > > On Thu, Jan 6, 2011 at 1:00 AM, David Winsemius >wrote: > > > >> > >> On Jan 5, 2011, at 9:38 PM, Eduardo de Oliveira Horta wrote: > >> > >> Hello, > >>> > >>> I want to save a pdf plot using Cairo, but the canvas of the saved file > >>> seems too large when compared to the actual plotted area. > >>> > >>> Is there a way to control the relation between the canvas size and the > >>> size > >>> of actual plotting area? > >>> > >>> > >> OS?, ... example? > >> > >> == > >> > >> David Winsemius, MD > >> West Hartford, CT > >> > >> > > > >[[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. > > > [[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] Cairo pdf canvas size
Something like this: u=seq(from=-pi, to=pi, length=1000) f=sin(u) Cairo("example.pdf", type="pdf",width=12,height=12,units="cm",dpi=300) par(cex.axis=.6,col.axis="grey",ann=FALSE, lwd=.25,bty="n", las=1, tcl=-.2, mgp=c(3,.5,0)) xlim=c(-pi,pi) ylim=round(c(min(f),max(f))) plot(u,f,xlim,ylim,type="l",col="firebrick3", axes=FALSE) axis(side=1, lwd=.25, col="darkgrey", at=seq(from=xlim[1], to=xlim[2], length=5)) axis(side=2, lwd=.25, col="darkgrey", at=seq(from=ylim[1], to=ylim[2], length=5)) abline(v=seq(from=xlim[1], to=xlim[2], length=5), lwd=.25,lty="dotted", col="grey") abline(h=seq(from=ylim[1], to=ylim[2], length=5), lwd=.25,lty="dotted", col="grey") dev.off() Notice how the canvas' margins are relatively far from the plotting area. Thanks, Eduardo On Thu, Jan 6, 2011 at 1:00 AM, David Winsemius wrote: > > On Jan 5, 2011, at 9:38 PM, Eduardo de Oliveira Horta wrote: > > Hello, >> >> I want to save a pdf plot using Cairo, but the canvas of the saved file >> seems too large when compared to the actual plotted area. >> >> Is there a way to control the relation between the canvas size and the >> size >> of actual plotting area? >> >> > OS?, ... example? > > == > > David Winsemius, MD > West Hartford, CT > > [[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] Cairo pdf canvas size
Hello, I want to save a pdf plot using Cairo, but the canvas of the saved file seems too large when compared to the actual plotted area. Is there a way to control the relation between the canvas size and the size of actual plotting area? Thanks in advance, and best regards, Eduardo Horta [[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] Adding lines in ggplot2
I thank you all for the insightful answers. I'm quite a rookie in R and have built a code that didn't take data frames into account. But I suppose I'm now convinced that they're actually a practical structure for organizing the data... so I'll adhere to the Data Frame Club soon enough. Best regards, Eduardo Horta On Wed, Jan 5, 2011 at 11:01 AM, Dennis Murphy wrote: > It was gently suggested to me in a private message that to achieve > *complete* control over the inputs and outputs in R graphics one should be > using grid graphics. I concur with that suggestion and wish to amend my > previous statement accordingly. > > With kindest thanks, > Dennis > > On Wed, Jan 5, 2011 at 3:02 AM, Dennis Murphy wrote: > > > Hi Bert: > > > > On Tue, Jan 4, 2011 at 8:39 PM, Bert Gunter >wrote: > > > >> Dennis: > >> > >> Can't speak to ggplot2, but your comments regarding lattice are not > >> quite correct. Many if not all of lattice's basic plot functions are > >> generic, which means that one has essentially complete latitude to > >> define plotting methods for arbitrary data structures. For example, > >> there is an xyplot.ts method for time series -- class ts -- data. > >> > >> Of course, for most lattice methods, the data do naturally come in a > >> data frame, and a standard lattice argument is to give a frame from > >> which to pull the data. But this is not required. > >> > >> I'm aware of that, but thank you for clarifying matters. I didn't state > > explicitly whether lattice required data frame input or not (my lattice > > example indicated no and indeed it does not), but the message was > evidently > > muddled further down the post. Your comments speak to some of the > > differences in the design and philosophy of lattice and ggplot2, and I > have > > no disagreement with your remarks about lattice. > > > > The point I was trying to make was that by using data frames and the > > several packages/base functions that support their manipulation, one can > > simplify the coding of graphics within both ggplot2 and lattice. There > are > > many things one can do with data frames that one cannot with vectors, as > you > > well know - e.g., extensions with new data (rbind) or new variables > > (cbind/transform, etc.), or reshaping, among others. These features can > be > > used to advantage in both ggplot2 and lattice. The OP's example is a > simple > > one - had he used > > > > df <- data.frame(x = sqrt(1:10), y = log(1:10)) # oops, forgot > 1:10... > > > > qplot(as.numeric(rownames(df)), x, data = df, geom = 'line', colour = > > I('darkgreen')) # ...but it's OK > > # or > > xyplot(x ~ as.numeric(rownames(x)), data = df, type = 'l', col.line = > > 'darkgreen') > > > > there would have been no problem. A little inconvenient for a new user, > > maybe, but hardly 'very restrictive'. > > > > > > As for other types of R data objects that are not data frames, offhand I > > can't think of too many that are incapable of being converted to data > frames > > somehow for the purposes of graphics, although I wouldn't be remotely > > surprised if some existed. [For example, one can extract fitted values, > > residuals and perhaps a model matrix from a model object and place the > > results in a data frame.] ggplot2 has a fortify() method to allow one to > > transform data objects for use in the package. There is some discussion > in > > Chapter 9 of Hadley's book, but I'm not in a position to add insight as I > > haven't used it personally. > > > > I do think this is a fair statement, though, and it's been said before: > if > > one wants *complete* control and flexibility of inputs and outputs, use > base > > graphics. Both lattice and ggplot2, by virtue of being structured > graphics > > systems, impose certain constraints (e.g., default actions) on the user > > which are system-dependent. Prof. Vardeman's quote still applies :) > > > > Dennis > > > > > > > > > > -- Bert > >> > >> > > >> > Please explain to me how > >> > > >> > df <- data.frame(x, y, index = 1:10) > >> > qplot(index, x, geom = 'line', ...) > >> > > >> > is 'very restrictive'. Lattice and ggplot2 are *structured* graphics > >> systems > >> > - to get the gains that they provide, there are some costs. I don't > >> perceive > >> > organization of data into a data frame as being restrictive - in fact, > >> if > >> > you learn how to construct data for input into ggplot2 to simplify the > >> code > >> > for labeling variables and legends, the data frame requirement is > >> actually a > >> > benefit rather than a restriction. Moreover, one can use the plyr and > >> > reshape(2) packages to reshape or condense data frames to provide even > >> more > >> > flexibility and freedom to produce ggplot2 and lattice graphics. In > >> > addition, the documentation for ggplot2 is quite explicit about > >> requiring > >> > data frames for input, so it is behaving as documented. The complexity > >> (and > >> > interaction) of the graphics code probably has something t
[R] Adding lines in ggplot2
Hello, this is probably a recurrent question, but I couldn't find any answers that didn't involve the expression "data frame"... so perhaps I'm looking for something new here. I wanted to find a code equivalent to > x=sqrt(1:10) > y=log(1:10) > plot(1:10, x, type="lines", col="darkgreen") > lines(1:10, y, col="red") to use with ggplot2. I've tried > x=sqrt(1:10) > y=log(1:10) > qplot(1:10, x, geom="line", colour=I("darkgreen")) > geom_line(1:10, y, colour="red") Error: ggplot2 doesn't know how to deal with data of class numeric but it seems that the "data frame restriction" is really very restrictive here. Any solutions that don't imply using as.data.frame to my data? Thanks in advance, and best regards! Eduardo Horta [[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] Saving objects inside a list
Hello, I've contacted the guys from RKWard. Below I paste the answer Thomas Friedrichsmeier gave me. --- Hi, the problem appears to be our use of "active bindings" (see ?makeActiveBinding). Internally, RKWard replaces all objects inside .GlobalEnv by active bindings. This allows us to find out, when the objects get modified. For almost all purposes, these active bindings behave just like the regular object, but apparently, as.list() copies the accessor functions, instead. I do wonder whether that is the expected behavior of as.list()... Either way, RKWard will probably switch to a different strategy for detecting when objects get modified, in the not-too-distant future. The problem should go away, then. Meanwhile, perhaps you can work around the problem using code like this: oblist <- sapply (ls (all.names=TRUE), function (x) get (x), simplify=FALSE) Regards Thomas On Tue, Jan 4, 2011 at 2:54 PM, William Dunlap wrote: > Under RKWard, do you get (at the command line) > > environment() > > If environment() doesn't evaluate to .GlobalEnv's > value then > as.list(environment()) > may show the B=1000. It may be that RKWard doesn't > use .GlobalEnv in the usual way. > > Bill Dunlap > Spotfire, TIBCO Software > wdunlap tibco.com > > > > -Original Message- > > From: r-help-boun...@r-project.org > > [mailto:r-help-boun...@r-project.org] On Behalf Of Eduardo de > > Oliveira Horta > > Sent: Tuesday, January 04, 2011 6:25 AM > > To: r-help@r-project.org > > Subject: Re: [R] Saving objects inside a list > > > > Hello, (and a happy new year for you too!) > > > > Apparently the problem is happening only within my RKWard sessions: > > > B = 1000 > > > oblist = as.list(.GlobalEnv) > > > str(oblist) > > List of 1 > > $ B:function (value) > > > oblist$B > > function (value) > > { > > if (!missing(value)) { > > assign(k, value, envir = .rk.watched.symbols) > > .rk.do.call("ws", k) > > invisible(value) > > } > > else { > > get(k, envir = .rk.watched.symbols) > > } > > } > > > > > > Now the same code in a regular Rgui session: > > > B = 1000 > > > oblist = as.list(.GlobalEnv) > > > str(oblist) > > List of 1 > > $ B: num 1000 > > > oblist$B > > [1] 1000 > > > > Problem solved? > > > > Best regards, > > > > Eduardo Horta > > > > On Tue, Jan 4, 2011 at 9:41 AM, Olivier ETERRADOSSI < > > olivier.eterrado...@mines-ales.fr> wrote: > > > > > Message: 42 > > >> Date: Mon, 3 Jan 2011 18:58:04 -0200 > > >> From: Eduardo de Oliveira Horta > > >> > > >> To: r-help > > >> Subject: Re: [R] Saving objects inside a list > > >> Message-ID: > > >> > > > > >> Content-Type: text/plain > > >> > > >> > > >> sapply(ls(),get) works fine. Thanks. > > >> > > >> ps: the as.list and the eapply suggestions didn't work. > > >> > > > Hi Eduardo (and all the best for this new year), > > > > > > are you sure the as.list and eapply solutions didn't work ? > > On my machine > > > they produce a list but in "reverse order" compared to the result of > > > ls(),...maybe it's the same with you : > > > > > > names(as.list(.GlobalEnv))[6] is the name of the 6th > > variable FROM THE END > > > of ls(). > > > > > > Regards. Olivier > > > > > > -- > > > Olivier ETERRADOSSI > > > Maître-Assistant > > > animateur du groupe Sensomines (Institut Carnot M.I.N.E.S) > > > - > > > CMGD > > > Pôle "Matériaux Polymères Avancés" > > > axe "Propriétés Psycho-Sensorielles des Matériaux" > > > - > > > Ecole des Mines d'Alès > > > Hélioparc, 2 av. P. Angot, F-64053 PAU CEDEX 9 > > > tel std: +33 (0)5.59.30.54.25 > > > tel direct: +33 (0)5.59.30.90.35 > > > fax: +33 (0)5.59.30.63.68 > > > http://www.mines-ales.fr > > > e-mail : olivier.eterrado...@mines-ales.fr > > > > > > > > > > > > > [[alternative HTML version deleted]] > > > > > [[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] Saving objects inside a list
Hello, (and a happy new year for you too!) Apparently the problem is happening only within my RKWard sessions: > B = 1000 > oblist = as.list(.GlobalEnv) > str(oblist) List of 1 $ B:function (value) > oblist$B function (value) { if (!missing(value)) { assign(k, value, envir = .rk.watched.symbols) .rk.do.call("ws", k) invisible(value) } else { get(k, envir = .rk.watched.symbols) } } Now the same code in a regular Rgui session: > B = 1000 > oblist = as.list(.GlobalEnv) > str(oblist) List of 1 $ B: num 1000 > oblist$B [1] 1000 Problem solved? Best regards, Eduardo Horta On Tue, Jan 4, 2011 at 9:41 AM, Olivier ETERRADOSSI < olivier.eterrado...@mines-ales.fr> wrote: > Message: 42 >> Date: Mon, 3 Jan 2011 18:58:04 -0200 >> From: Eduardo de Oliveira Horta >> >> To: r-help >> Subject: Re: [R] Saving objects inside a list >> Message-ID: >> >> Content-Type: text/plain >> >> >> sapply(ls(),get) works fine. Thanks. >> >> ps: the as.list and the eapply suggestions didn't work. >> > Hi Eduardo (and all the best for this new year), > > are you sure the as.list and eapply solutions didn't work ? On my machine > they produce a list but in "reverse order" compared to the result of > ls(),...maybe it's the same with you : > > names(as.list(.GlobalEnv))[6] is the name of the 6th variable FROM THE END > of ls(). > > Regards. Olivier > > -- > Olivier ETERRADOSSI > Maître-Assistant > animateur du groupe Sensomines (Institut Carnot M.I.N.E.S) > - > CMGD > Pôle "Matériaux Polymères Avancés" > axe "Propriétés Psycho-Sensorielles des Matériaux" > - > Ecole des Mines d'Alès > Hélioparc, 2 av. P. Angot, F-64053 PAU CEDEX 9 > tel std: +33 (0)5.59.30.54.25 > tel direct: +33 (0)5.59.30.90.35 > fax: +33 (0)5.59.30.63.68 > http://www.mines-ales.fr > e-mail : olivier.eterrado...@mines-ales.fr > > > [[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] Saving objects inside a list
sapply(ls(),get) works fine. Thanks. ps: the as.list and the eapply suggestions didn't work. On Mon, Jan 3, 2011 at 3:56 PM, Jorge Ivan Velez wrote: > Hi Eduardo, > > Try > > r <- ls() > result <- sapply(r, get) > result > > HTH, > Jorge > > > On Mon, Jan 3, 2011 at 12:25 PM, Eduardo de Oliveira Horta <> wrote: > >> Hello there, >> >> any ideas on how to save all the objects on my workspace inside a list >> object? >> >> For example, say my workspace is as follows >> ls() >> [1] "x" "y" "z" >> >> and suppose I want to put these objects inside a list object, say >> >> object.list <- list() >> >> without having to explicitly write down their names as in >> >> object.list$x = x >> object.list$y = y >> object.list$z = z >> >> Is this possible? >> >> Thanks in advance, >> >> Eduardo Horta >> >>[[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. >> > > [[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] Saving objects inside a list
Thanks, but this is still too restrictive... I wanted something that could actually save objects with arbitrary names inside a list object... On Mon, Jan 3, 2011 at 3:39 PM, Henrique Dallazuanna wrote: > Try this: > > sapply(ls(pattern = "x|y|z"), get, simplify = F) > > > On Mon, Jan 3, 2011 at 3:25 PM, Eduardo de Oliveira Horta < > eduardo.oliveiraho...@gmail.com> wrote: > >> Hello there, >> >> any ideas on how to save all the objects on my workspace inside a list >> object? >> >> For example, say my workspace is as follows >> ls() >> [1] "x" "y" "z" >> >> and suppose I want to put these objects inside a list object, say >> >> object.list <- list() >> >> without having to explicitly write down their names as in >> >> object.list$x = x >> object.list$y = y >> object.list$z = z >> >> Is this possible? >> >> Thanks in advance, >> >> Eduardo Horta >> >>[[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] Saving objects inside a list
Hello there, any ideas on how to save all the objects on my workspace inside a list object? For example, say my workspace is as follows ls() [1] "x" "y" "z" and suppose I want to put these objects inside a list object, say object.list <- list() without having to explicitly write down their names as in object.list$x = x object.list$y = y object.list$z = z Is this possible? Thanks in advance, Eduardo Horta [[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] Finding indexes of minum and maximum elements of an array
Hello there I wish to get the "coordinates" of the minimum element of an array. For example, if the array were > H = array(c(8:5,1:4),dim=c(2,2,2)) > H , , 1 [,1] [,2] [1,]86 [2,]75 , , 2 [,1] [,2] [1,]13 [2,]24 then > min(H) [1] 1 and > max(H) [1] 8 Say "idx" were the function I'm looking for. Then, what I'm expecting is > idx(min(H)) [1] 1 1 2 > idx(max(H)) [1] 1 1 1 Thanks in advance, Eduardo de Oliveira Horta [[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] Removing elements of a list object
Thanks! On Thu, Dec 23, 2010 at 3:24 PM, Henrique Dallazuanna wrote: > Try this: > > x$second <- NULL > > > On Thu, Dec 23, 2010 at 3:21 PM, Eduardo de Oliveira Horta < > eduardo.oliveiraho...@gmail.com> wrote: > >> Hello, >> >> say I have an object >> >> > x = list(first = 10, second = 20, third = "Yeah!") >> >> and want to remove the $second element of that list. My first try was, of >> course, >> >> > rm(x$second) >> >> which gave me the following error message >> >> > Error in rm(x$second) : ... must contain names or character strings >> >> Any ideas here, folks? >> >> Best regards, and Merry Christmas! >> >> Eduardo Horta >> >>[[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] Integration with LaTex and LyX
Thanks! On Mon, Dec 13, 2010 at 7:10 PM, Yihui Xie wrote: > I tried hard to write an automagic script to configure LyX so that you > don't need to go to the instructions on CRAN > (http://cran.r-project.org/contrib/extra/lyx/): > > > http://yihui.name/en/2010/10/how-to-start-using-pgfsweave-in-lyx-in-one-minute/ > > This works for LyX 1.6.x and major OS'es with probability 95%. > > There will be substantial changes in LyX 2.0, and I will need to > modify my configurations after LyX 2.0 is out (hopefully early next > year). > > Regards, > Yihui > -- > Yihui Xie > Phone: 515-294-2465 Web: http://yihui.name > Department of Statistics, Iowa State University > 2215 Snedecor Hall, Ames, IA > > > > On Mon, Dec 13, 2010 at 9:27 AM, Eduardo de Oliveira Horta > wrote: > > Hello, > > > > Are there any packages which allow for a good integration between R and > > LaTex / LyX? I'm interested mainly in automatic (automagic?) imports of > > plots/graphics. > > > > Thanks in advance and best regards, > > > > Eduardo de Oliveira Horta > > > >[[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. > > > [[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] Removing elements of a list object
Hello, say I have an object > x = list(first = 10, second = 20, third = "Yeah!") and want to remove the $second element of that list. My first try was, of course, > rm(x$second) which gave me the following error message > Error in rm(x$second) : ... must contain names or character strings Any ideas here, folks? Best regards, and Merry Christmas! Eduardo Horta [[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] Integrate two function in R
I guess what you have is g <- function(x){ 2*x-3 } s <- function(x){ 5*x^2+2 } and what you want is f<-function(x){ g(x)*s(x) } integrate(f,a,b) Try that and see if it works. If not (that is, if your actual g and s are not as in the example), maybe you'll have to do this: integrate(Vectorize(f),a,b) On Thu, Dec 16, 2010 at 10:27 AM, Alaios wrote: > Hello I have two function in R > like > g(x)=2x-3 > and s(x)=5x^2+2 > > and I want to find the integrafl of the g(x)*s(x) inside the interval of > [a,b] > > Could you please help me find the proper function? > > I would like to thank you in advance for your help > > Regards > Alex > > > >[[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. > [[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] Integration with LaTex and LyX
Hello, Are there any packages which allow for a good integration between R and LaTex / LyX? I'm interested mainly in automatic (automagic?) imports of plots/graphics. Thanks in advance and best regards, Eduardo de Oliveira Horta [[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] Two time measures
Hello! I have a csv file of intra-day financial data (5-min closing prices) that looks like this: (obs - the dates are formated as day/month/year, as is usual here in Brazil) Date;Time;Close 01/09/2009;10:00;56567 01/09/2009;10:05;56463 01/09/2009;10:10;56370 ##(goes on all day) 01/09/2009;16:45;55771 01/09/2009;16:50;55823 01/09/2009;16:55;55814 ##(jumps to the subsequent day) 02/09/2009;10:00;55626 02/09/2009;10:05;55723 02/09/2009;10:10;55659 ##(goes on all day) 02/09/2009;16:45;55742 02/09/2009;16:50;55717 02/09/2009;16:55;55385 ## (and so on to the next day) I would like to store the intra-day 5-min prices into a list, where each element would represent one day, something like list[[1]] "price at time 1, day 1" "price at time 2, day 1" ... "price at time n_1, day 1" list[[2]] "price at time 1, day 2" "price at time 2, day 2" ... "price at time n_2, day 2" and so on. As the "n_1", "n_2", etc, suggest, each day have its own number of observations (this reflects the fact that the market may open and close at varying daytimes). I have guessed that a list would be a better way to store my data, since a matrix would be filled with NA's and that is not exactly what I'm looking for. Thanks in advance, and best regards, Eduardo Horta [[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] On efficiency, Vectorize and loops
In my last e-mails, I have asked for help regarding 1. 'defining functions inside loops' 2. 'integrating functions / vector arithmetics' 3. 'vectors out of lists?' 4. 'numerical integration' Since some of these topics seemed to be relevant (I'm guessing by the # of replies I got), I'm posting a modified section of my code. Any thoughts on improvements would be highly welcome! In the end of this code I put a little test on comparing the different functions I must integrate. I'm really interested in efficiency since I'll need to do that 'inner.product' operation 95*95*5 times on each of my B bootstrap loops, where B should be 1000 but is more likely to be 500 or 200 if I'm willing to graduate before March! # 'code0' is used for simulation and test purposes only; # The model is the same as in Bathia, Yao, Ziegelmann p.13 # The code used for estimation is 'code1' rm(list=ls(all=TRUE)) n<-100 # Number of observations d<-4 # Dimension of X a<-0 # Lower bound b<-1 # Upper bound p<-5 # [See Bathia, Yao, Ziegelmann p. 5) ### # Building the error function 'epsilon' ### # Building the vector process 'Z' (which is a iiN(0,I_d) vector process) # Time varies columnwise Z<-matrix(rnorm(10*n),nrow=10,ncol=n) # Defining the deterministic base functions 'zeta' zeta<-function(u,i){ sqrt(2)+sin(pi*i*u) } zeta2<-function(i){force(i); function(u){ sqrt(2)+sin(pi*outer(i,u)) } } zeta3<-function(u,i){ sqrt(2)+sin(pi*outer(i,u)) } # Building the random functional process 'epsilon' epsilon<-lapply(1:n, function(t)local({force(t); function(u){ epsilon<-0 for (j in 1:10){ epsilon<-epsilon+2^(1-j)*Z[j,t]*zeta(u,j) } epsilon<-epsilon } })) epsilon2<-lapply(1:n, function(t)local({force(t); function(u){ crossprod(2^(1-(1:10))*Z[,t],zeta2(1:10)(u)) } })) epsilon3<-lapply(1:n, function(t)local({force(t); function(u){ crossprod(2^(1-(1:10))*Z[,t],zeta3(u,1:10)) } })) ### # Building the function 'X' ### # Building the vector process 'xi'. Time varies columnwise. # Each line is a realization of an AR(1) process. xi<-matrix(0,nrow=d,ncol=n) for (i in 1:d){ theta<-(-1)^i * (.9 - .5*i/d) xi[i,]<-arima.sim(model=list(ar=theta), n, rand.gen = rnorm) } rm(i, theta) #Defining the deterministic base functions 'phi' phi<-function(u,i){ sqrt(2)*cos(pi*i*u) } phi2<-function(i){force(i); function(u){ sqrt(2)*cos(pi*outer(i,u)) } } phi3<-function(u,i){ sqrt(2)*cos(pi*outer(i,u)) } # Building the random functional process 'X' X<-lapply(1:n, function(t)local({force(t); function(u){ X<-0 for (i in 1:d){ X<-X+xi[i,t]*phi(u,i) } X<-X } })) X2<-lapply(1:n, function(t)local({force(t); function(u){ crossprod(xi[,t],phi2(1:d)(u)) } })) X3<-lapply(1:n, function(t)local({force(t); function(u){ crossprod(xi[,t],phi3(u,1:d)) } })) # # Defining the functional process 'Y' # Y<-lapply(1:n, function(t)local({force(t); function(u){ X[[t]](u)+epsilon[[t]](u) } })) Y2<-lapply(1:n, function(t)local({force(t); function(u){ X2[[t]](u)+epsilon2[[t]](u) } })) Y3<-lapply(1:n, function(t)local({force(t); function(u){ X3[[t]](u)+epsilon3[[t]](u) } })) Y4<-lapply(1:n, function(t)local({force(t); function(u){ crossprod(xi[,t],sqrt(2)*cos(pi*outer(1:d,u))) + crossprod(2^(1-(1:10))*Z[,t],sqrt(2)+sin(pi*outer(1:10,u))) } })) ## # remove later Ybar<-function(u){ Ybar<-0 for (t in 1:n){ Ybar<-Ybar+Y[[t]](u) } Ybar<-1/n*Ybar } Ybar2<-function(u){ Ybar2<-0 for (t in 1:n){ Ybar2<-Ybar2+Y2[[t]](u) } Ybar2<-1/n*Ybar2 } Ybar3<-function(u){ Ybar3<-0 for (t in 1:n){ Ybar3<-Ybar3+Y3[[t]](u) } Ybar3<-1/n*Ybar3 } Ybar4<-function(u){ Ybar4<-0 for (t in 1:n){ Ybar4<-Ybar4+Y4[[t]](u) } Ybar4<-1/n*Ybar4 } # Defining the inner product on L^2([a,b]) inner.product<-function(f,g){ core<-function(u){ core<-f(u)*g(u) } inner.product<-integrate(core,a,b)$value } ### # Defining the deviation functions (Y[[t]] - Ybar) used as an input # by the function inner.product below Y.dev<-lapply(1:n, function(t)local({force(t); function(u){ Y[[t]](u)-Ybar(u) } })) Y.dev2<-lapply(1:n, function(t)local({force(t); function(u){ Y2[[t]](u)-Ybar2(u) } })) Y.dev3<-lapply(1:n, function(t)local({force(t); function(u){ Y3[[t]](u)-Ybar3(u) } })) Y.dev4<-lapply(1:n, function(t)local({force(t); function(u){ Y4[[t]](u)-Ybar4(u) } })) print(inner.product(Y.dev[[n]], Y.dev[[n]])) print(inner.product(Y.dev2[[n]], Y.dev2[[n]])) print(inner.product(Y.dev3[[n]], Y.dev3[[n]])) print(inner.product(Y.dev4[[n]], Y.dev4[[n]])) system.time(for(i in 1:100)inner.product(Y.dev[[n]], Y.dev[[n]])) system.time(for(i in 1:100)inn
[R] Fwd: Numerical integration
-- Forwarded message -- From: Eduardo de Oliveira Horta Date: Wed, Nov 17, 2010 at 3:59 PM Subject: Re: [R] Numerical integration To: David Winsemius It works, however is not very efficient for the problem I'm working with, since it is the same as vectorizing the integrand before applying "integrate". Any other thoughts? Efficiency would be highly welcome! Thanks again, Eduardo Horta On Wed, Nov 17, 2010 at 2:10 PM, Eduardo de Oliveira Horta < eduardo.oliveiraho...@gmail.com> wrote: > Thanks! I'll take a look into it and let you know if it works. > > > On Wed, Nov 17, 2010 at 1:57 PM, David Winsemius > wrote: > >> >> On Nov 17, 2010, at 6:44 AM, Eduardo de Oliveira Horta wrote: >> >> Hi! >>> >>> I was wondering if there are any other functions for numerical >>> integration, >>> besides 'integrate' from the stats package, but which wouldn't require >>> the >>> integrand to be vectorized. Oh, and must be capable of integrating over >>> (-inf,+inf). >>> >> >> You could modify integrate to suit you specifications, Just substitute >> this at the beginning of the integrate: >> >> integrateV <- function (f, lower, upper, ..., subdivisions = 100, rel.tol >> = .Machine$double.eps^0.25, >>abs.tol = rel.tol, stop.on.error = TRUE, keep.xy = FALSE, >>aux = NULL) >> { >>f <- match.fun(f) >>### New material >>options(show.error.messages = FALSE) >>if( class(try(integrate(f, upper, lower))) == 'try-error') {f <- >> Vectorize(f)} >>options(show.error.messages = TRUE) >>### End new material >>ff <- function(x) f(x, ...) >> . >> . >> . >> >> >> Passes both your requirements: >> > zz<- function(x) 2.0 # the function that fails in the integrate help >> page >> > try(integrateV(zz, 0, 1)) >> 2 with absolute error < 2.2e-14 >> >> > zz<- function(x) dnorm(x) # test of infinite range capacity >> > try(integrateV(zz, -Inf, Inf)) >> 1 with absolute error < 9.4e-05 >> >> >> -- >> >> David Winsemius, MD >> West Hartford, CT >> >> > [[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] Vectors out of lists?
Thanks. I wanted to avoid loops (even inside functions) because I thought they were much slower than vector operations, and I really need an efficient code (not an exercise!). However, after a few tentatives I'm coming to the conclusion that loops are actually MORE efficient (at least in the type of problem I'm working with). Any thoughts on this? Best regards, Eduardo Horta On Wed, Nov 17, 2010 at 3:42 PM, William Dunlap wrote: > Don't fixate on avoiding loops. Bury them in a function > so you don't have to see them and then you just want something > that does the right thing quickly enough. (I'm assuming > this is not a homework/puzzle type problem where you are not > allowed to use loops). E.g., the following does the job (with > no error checking): > Ybar <- function(u, Y) { > result <- Y[[1]](u) > for(Yi in Y[-1]) result <- result + Yi(u) > result/length(Y) > } > > You could probably shoehorn this into a call to Reduce but there > must be a for loop in Reduce. > > Bill Dunlap > Spotfire, TIBCO Software > wdunlap tibco.com > > > -- > *From:* Eduardo de Oliveira Horta [mailto:eduardo.oliveiraho...@gmail.com] > > *Sent:* Tuesday, November 16, 2010 4:15 PM > *To:* David Winsemius > *Cc:* Phil Spector; r-help@r-project.org; www...@gmail.com; William Dunlap > > *Subject:* Re: [R] Vectors out of lists? > > Thanks, guys... but it seems these suggestions won't work. > > Let me try to be more specific with a simple example: > > Y<-list() > Y[[1]]<-function(u) sqrt(u) > Y[[2]]<-function(u) sin(u) > Y[[3]]<-function(u) 1/2*u > > I wanted something equivalent to > > Ybar<-function(u){ >1/3*(Y[[1]](u) + Y[[2]](u) + Y[[3]](u)) > } > > but with arbitrary length(Y) and without using any loops. Also, I can't > allow for discretization, since I must be able to evaluate Ybar at any u, as > I'm going to integrate it with the function "integrate". > > Thanks again, > > Eduardo Horta > > [[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] Numerical integration
Hi! I was wondering if there are any other functions for numerical integration, besides 'integrate' from the stats package, but which wouldn't require the integrand to be vectorized. Oh, and must be capable of integrating over (-inf,+inf). Thanks in advance, Eduardo Horta [[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] Vectors out of lists?
Thank you very much! Works like a charm! On Tue, Nov 16, 2010 at 10:24 PM, Phil Spector wrote: > Eduardo - > Thanks for the reproducible example! > >> Y<-list() >> Y[[1]]<-function(u) sqrt(u) >> Y[[2]]<-function(u) sin(u) >> Y[[3]]<-function(u) 1/2*u >> Ybar = function(u)mean(sapply(Y,function(fun)fun(u))) >> > > Since integrate requires a function which accepts a vector > and returns a vector, we'd need to use Vectorize() before > trying to integrate: > > integrate(Vectorize(Ybar),0,1) >> > 0.4587882 with absolute error < 5.6e-05 > > >- Phil Spector > Statistical Computing Facility > Department of Statistics > UC Berkeley > spec...@stat.berkeley.edu > > > > > On Tue, 16 Nov 2010, Eduardo de Oliveira Horta wrote: > > Thanks, guys... but it seems these suggestions won't work. >> >> Let me try to be more specific with a simple example: >> >> Y<-list() >> Y[[1]]<-function(u) sqrt(u) >> Y[[2]]<-function(u) sin(u) >> Y[[3]]<-function(u) 1/2*u >> >> I wanted something equivalent to >> >> Ybar<-function(u){ >>1/3*(Y[[1]](u) + Y[[2]](u) + Y[[3]](u)) >> } >> >> but with arbitrary length(Y) and without using any loops. Also, I can't >> allow >> for discretization, since I must be able to evaluate Ybar at any u, as I'm >> going to integrate it with the function "integrate". >> >> Thanks again, >> >> Eduardo Horta >> >> [[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] Vectors out of lists?
Thanks, guys... but it seems these suggestions won't work. Let me try to be more specific with a simple example: Y<-list() Y[[1]]<-function(u) sqrt(u) Y[[2]]<-function(u) sin(u) Y[[3]]<-function(u) 1/2*u I wanted something equivalent to Ybar<-function(u){ 1/3*(Y[[1]](u) + Y[[2]](u) + Y[[3]](u)) } but with arbitrary length(Y) and without using any loops. Also, I can't allow for discretization, since I must be able to evaluate Ybar at any u, as I'm going to integrate it with the function "integrate". Thanks again, Eduardo Horta [[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] Vectors out of lists?
Hello there I have a list, Y, and each component of that list is a real-valued function (that is, Y[[i]](u) returns a number). I was wishing to build the mean function and the first thing I thought of was Ybar<-function(u){ mean(Y[[1:n]](u)) } but obviously this doesn't work, since Y[[1:n]] is not allowed at all. Any elegant suggestions? I really would like to avoid something like Ybar<-function(u){ for (i in 1:n){ Ybar<-Ybar + Ybar[[i]](u) } Ybar<-1/n*Ybar } Thanks in advance! Best regards, Eduardo Horta [[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] Integrating functions / vector arithmetic
Thanks, I'll try that. Regarding your question "Why are you using assignments to indicate the return values of functions?", I'd probably answer that it is a matlab vice... But I'll change my habits soon enough! Best regards, Eduardo Horta On Tue, Nov 16, 2010 at 12:27 PM, Erich Neuwirth < erich.neuwi...@univie.ac.at> wrote: > Some remarks: > Why are you using assignments to indicate the return values of functions? > This is R idiom: > > f<-function(u){ > > f<-0 > > for (j in 1:4){ > >f<-f+coeff[j]*(zeta(j)(u)) > > } > > f > > } > > > > If you only want the inner product of 2 vector, "outer" probably is an > overkill. > > g <- function(u){ > sum(coeff * zeta(1:4)(u)) > } > > should be enough. > > And plot(g) does not work because g is not vectorized. > > plot(Vectorize(g)) > > will work > > On Nov 16, 2010, at 1:18 AM, Eduardo de Oliveira Horta wrote: > > > Hello, > > > > I was trying to build some functions which I would like to integrate over > an > > interval using the function 'integrate' from the 'stats' package. As an > > example, please consider the function > > > > h(u)=sin(pi*u) + sqrt(2)*sin(pi*2*u) + sqrt(3)*sin(pi*3*u) + > 2*sin(pi*4*u) > > > > Two alternative ways to 'build' this function are as in f and g below: > > > > coeff<-sqrt(1:4) > > > > zeta<-function(i) {force(i); function(u){ > > zeta<-sqrt(2)+sin(pi*i*u) > > }} > > > > f<-function(u){ > > f<-0 > > for (j in 1:4){ > >f<-f+coeff[j]*(zeta(j)(u)) > > } > > f<-f > > } > > > > g<-function(u){ > > g<-crossprod(coeff,zeta(1:4)(u)) > > } > > > > Obviously, f and g are equivalent, but in the actual code I am writing, g > is > > much faster. However, I can't seem to integrate (neither to plot) g. In > > fact, these are the error messages I get: > > > >> print(f(.1)) > > [1] 4.443642 > >> print(g(.1)) > > [,1] > > [1,] 4.443642 > > > > Everything ok until here... but... > > > > When using plot(), I get this: > > > >> plot(f) #plots, as expected. > >> plot(g) > > Error in crossprod(coeff,zeta(1:4)(u)) : arguments not compatible > > Besides that: Warning message: > > In pi * i * u : > > longer object length is not a multiple of shorter object length > > > > When using integrate(), I get this: > > > >> integrate(f,0,1) > > 1.004172 with absolute error < 2.5e-13 > >> integrate(g,0,1) > > Error in crossprod(coeff,zeta(1:4)(u)) : arguments not compatible > > Besides that: Warning message: > > In pi * i * u : > > longer object length is not a multiple of shorter object length > >> > > > > I have already tried some simple 'solutions', for example to set > > g<-function(u){ > > vec1<-drop(coeff) > > vec2<-drop(zeta(1:4)(u)) > > g<-drop(crossprod(coeff,zeta(1:4)(u))) > > } > > > > as well as using the %*% operation, but these won't solve my problem. > > > > Any suggestions would be welcome. Thanks in advance, > > > > Eduardo Horta > > > > [[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. > > > > -- > Erich Neuwirth, University of Vienna > Faculty of Computer Science > Center for Computer Science Didactics and Learning Research > Visit our SunSITE at http://sunsite.univie.ac.at > Phone: +43-1-4277-39902 Fax: +43-1-4277-39459 > > [[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] Integrating functions / vector arithmetic
Thanks! Seems to work just fine! Best regards, Eduardo Horta On Mon, Nov 15, 2010 at 10:37 PM, David Winsemius wrote: > > On Nov 15, 2010, at 7:18 PM, Eduardo de Oliveira Horta wrote: > > Hello, >> >> I was trying to build some functions which I would like to integrate over >> an >> interval using the function 'integrate' from the 'stats' package. As an >> example, please consider the function >> >> h(u)=sin(pi*u) + sqrt(2)*sin(pi*2*u) + sqrt(3)*sin(pi*3*u) + 2*sin(pi*4*u) >> >> Two alternative ways to 'build' this function are as in f and g below: >> >> coeff<-sqrt(1:4) >> >> zeta<-function(i) {force(i); function(u){ >> zeta<-sqrt(2)+sin(pi*i*u) >> }} >> >> f<-function(u){ >> f<-0 >> for (j in 1:4){ >> f<-f+coeff[j]*(zeta(j)(u)) >> } >> f<-f >> } >> >> g<-function(u){ >> g<-crossprod(coeff,zeta(1:4)(u)) >> } >> >> Obviously, f and g are equivalent, but in the actual code I am writing, g >> is >> much faster. However, I can't seem to integrate (neither to plot) g. In >> fact, these are the error messages I get: >> >> print(f(.1)) >>> >> [1] 4.443642 >> >>> print(g(.1)) >>> >>[,1] >> [1,] 4.443642 >> >> Everything ok until here... but... >> >> When using plot(), I get this: >> >> plot(f) #plots, as expected. >>> plot(g) >>> >> > Try vectorizing g() > > > > g<-function(u){ >g<-crossprod(coeff,zeta(1:4)(u)) > } > > gV <- Vectorize(g) > > integrate(gV,0,1) > > ## 9.696303 with absolute error < 2.5e-13 > > You didn't say what you thought the analytic answer might be so I cannot > check it. > > -- > David. > > Error in crossprod(coeff,zeta(1:4)(u)) : arguments not compatible >> Besides that: Warning message: >> In pi * i * u : >> longer object length is not a multiple of shorter object length >> >> When using integrate(), I get this: >> >> integrate(f,0,1) >>> >> 1.004172 with absolute error < 2.5e-13 >> >>> integrate(g,0,1) >>> >> Error in crossprod(coeff,zeta(1:4)(u)) : arguments not compatible >> Besides that: Warning message: >> In pi * i * u : >> longer object length is not a multiple of shorter object length >> >>> >>> >> I have already tried some simple 'solutions', for example to set >> g<-function(u){ >> vec1<-drop(coeff) >> vec2<-drop(zeta(1:4)(u)) >> g<-drop(crossprod(coeff,zeta(1:4)(u))) >> } >> >> as well as using the %*% operation, but these won't solve my problem. >> >> Any suggestions would be welcome. Thanks in advance, >> >> Eduardo Horta >> >>[[alternative HTML version deleted]] >> > > David Winsemius, MD > West Hartford, CT > > [[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] Integrating functions / vector arithmetic
Hello, I was trying to build some functions which I would like to integrate over an interval using the function 'integrate' from the 'stats' package. As an example, please consider the function h(u)=sin(pi*u) + sqrt(2)*sin(pi*2*u) + sqrt(3)*sin(pi*3*u) + 2*sin(pi*4*u) Two alternative ways to 'build' this function are as in f and g below: coeff<-sqrt(1:4) zeta<-function(i) {force(i); function(u){ zeta<-sqrt(2)+sin(pi*i*u) }} f<-function(u){ f<-0 for (j in 1:4){ f<-f+coeff[j]*(zeta(j)(u)) } f<-f } g<-function(u){ g<-crossprod(coeff,zeta(1:4)(u)) } Obviously, f and g are equivalent, but in the actual code I am writing, g is much faster. However, I can't seem to integrate (neither to plot) g. In fact, these are the error messages I get: > print(f(.1)) [1] 4.443642 > print(g(.1)) [,1] [1,] 4.443642 Everything ok until here... but... When using plot(), I get this: > plot(f) #plots, as expected. > plot(g) Error in crossprod(coeff,zeta(1:4)(u)) : arguments not compatible Besides that: Warning message: In pi * i * u : longer object length is not a multiple of shorter object length When using integrate(), I get this: > integrate(f,0,1) 1.004172 with absolute error < 2.5e-13 > integrate(g,0,1) Error in crossprod(coeff,zeta(1:4)(u)) : arguments not compatible Besides that: Warning message: In pi * i * u : longer object length is not a multiple of shorter object length > I have already tried some simple 'solutions', for example to set g<-function(u){ vec1<-drop(coeff) vec2<-drop(zeta(1:4)(u)) g<-drop(crossprod(coeff,zeta(1:4)(u))) } as well as using the %*% operation, but these won't solve my problem. Any suggestions would be welcome. Thanks in advance, Eduardo Horta [[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] Defining functions inside loops
Thanks a lot for your readiness! Problem (apparently) solved! Best regards, Eduardo Horta On Mon, Nov 15, 2010 at 7:10 PM, William Dunlap wrote: > You could make f[[i]] be function(t)t^2+i for i in 1:10 > with > f <- lapply(1:10, function(i)local({ force(i) ; function(x)x^2+i})) > After that we get the correct results >> f[[7]](100:103) >[1] 10007 10208 10411 10616 > but looking at the function doesn't immdiately tell you > what 'i' is in the function >> f[[7]] >function (x) >x^2 + i > > You can find it in f[[7]]'s environment >> get("i", envir=environment(f[[7]])) >[1] 7 > > The call to force() in the call to local() is not > necessary in this case, although it can help in > other situations. > > Bill Dunlap > Spotfire, TIBCO Software > wdunlap tibco.com > > > -Original Message----- > > From: r-help-boun...@r-project.org > > [mailto:r-help-boun...@r-project.org] On Behalf Of Eduardo de > > Oliveira Horta > > Sent: Monday, November 15, 2010 12:50 PM > > To: r-help@r-project.org > > Subject: [R] Defining functions inside loops > > > > Hello, > > > > I was trying to define a set of functions inside a loop, with > > the loop index > > working as a parameter for each function. Below I post a > > simpler example, as > > to illustrate what I was intending: > > > > f<-list() > > for (i in 1:10){ > > f[[i]]<-function(t){ > > f[[i]]<-t^2+i > > } > > } > > rm(i) > > > > With that, I was expecting that f[[1]] would be a function > > defined by t^2+1, > > f[[2]] by t^2+2 and so on. However, the index i somehow > > doesn't "get in" the > > function definition on each loop, that is, the functions > > f[[1]] through > > f[[10]] are all defined by t^2+i. Thus, if I remove the > > object i from the > > workspace, I get an error when evaluating these functions. > > Otherwise, if > > don't remove the object i, it ends the loop with value equal > > to 10 and then > > f[[1]](t)=f[[2]](t)=...=f[[10]](t)=t^2+10. > > > > I am aware that I could simply put > > > > f<-function(u,i){ > > f<-t^2+i > > } > > > > but that's really not what I want. > > > > Any help would be appreciated. Thanks in advance, > > > > Eduardo Horta > > > > [[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. > > > [[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] Defining functions inside loops
Hello, I was trying to define a set of functions inside a loop, with the loop index working as a parameter for each function. Below I post a simpler example, as to illustrate what I was intending: f<-list() for (i in 1:10){ f[[i]]<-function(t){ f[[i]]<-t^2+i } } rm(i) With that, I was expecting that f[[1]] would be a function defined by t^2+1, f[[2]] by t^2+2 and so on. However, the index i somehow doesn't "get in" the function definition on each loop, that is, the functions f[[1]] through f[[10]] are all defined by t^2+i. Thus, if I remove the object i from the workspace, I get an error when evaluating these functions. Otherwise, if don't remove the object i, it ends the loop with value equal to 10 and then f[[1]](t)=f[[2]](t)=...=f[[10]](t)=t^2+10. I am aware that I could simply put f<-function(u,i){ f<-t^2+i } but that's really not what I want. Any help would be appreciated. Thanks in advance, Eduardo Horta [[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.