Re: [R] computing distance in miles or km between 2 street addre
On 9/6/07, Rolf Turner [EMAIL PROTECTED] wrote: On 7/09/2007, at 10:17 AM, (Ted Harding) wrote: On 06-Sep-07 18:42:32, Philip James Smith wrote: Hi R-ers: I need to compute the distance between 2 street addresses in either km or miles. I do not care if the distance is a shortest driving route or if it is as the crow flies. Does anybody know how to do this? Can it be done in R? I have thousands of addresses, so I think that Mapquest is out of the question! Please rely to: [EMAIL PROTECTED] Thank you! Phil Smith That's a somewhat ill-posed question! You will for a start need a database of some kind, either of geographical locations (coordinates) of street addresses, or of the metric of the road network with capability to identify the street addresses in the database. snip As far as I know, R has no database relevant to street addresses! But Ted! Don't you know that statistics in general and R in particular are supposed to be able to ***work MAGIC***??? :-) :-) :-) Wow! I didn't know that. What's the function call? /Henrik cheers, Rolf ## Attention:\ This e-mail message is privileged and confidenti...{{dropped}} __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] quantile() returns a value outside the data range
Hi, yes, it is all about numerical accuracy; x - c(6.402611, 6.402611, 6.420587) x001 - sapply(1:9, function(type) quantile(x, probs=0.01, type=type)) names(x001) - NULL print(x001) ## [1] 6.402611 6.402611 6.402611 6.402611 6.402611 ## [6] 6.402611 6.402611 6.402611 6.402611 diff(x001) ## [1] 0.00e+00 0.00e+00 0.00e+00 ## [4] 0.00e+00 -8.881784e-16 8.881784e-16 ## [7] -8.881784e-16 8.881784e-16 So, (even) the different types of 1%-quantile estimates of 'x' differ. Thus, the equality part of your comparison (=) (with sort(x)[1]) can only return TRUE for some of the elements, but not all. The following should do for all.equal() for '=': Assume 'x' and 'y' are scalars for simplicity. To test 'x == y' with some precision, you use all.equal(x,y, tolerance=eps), which tests |x-y| eps = -eps x-y eps where eps is a small positive number specifying your precision. To test 'x = y' (= 'x - y = 0') with some precision, you want to test x - y = eps, i.e. lessOrEqual - function(x, y, tolerance=.Machine$double.eps^0.5, ...) { (x - y = tolerance); } sapply(x, x001, lessOrEqual) sapply(x, lessOrEqual, x001) ## [,1] [,2] [,3] ## [1,] TRUE TRUE FALSE ## [2,] TRUE TRUE FALSE ## [3,] TRUE TRUE FALSE ## [4,] TRUE TRUE FALSE ## [5,] TRUE TRUE FALSE ## [6,] TRUE TRUE FALSE ## [7,] TRUE TRUE FALSE ## [8,] TRUE TRUE FALSE ## [9,] TRUE TRUE FALSE Next time, please give a cut'n'paste reproducible example. /Henrik On 8/21/07, Jenny Bryan [EMAIL PROTECTED] wrote: Hello, I am getting an unexpected result from quantile(). Specifically, the return value falls outside the range of the data, which I wouldn't have thought possible for a weighted average of 2 order statistics. Is this an unintended accuracy issue or am I being too casual in my comparison (is there some analogue of 'all.equal' for =)? Small example: foo - h2[,17][h2$plate==222] # some data I have, details not interesting foo - sort(foo)[1:3]# can demo with the 3 smallest values yo - data.frame(matrix(foo,nrow=length(foo),ncol=10)) fooQtile - rep(0,9) for(i in 1:9) { # compute 0.01 quantile, for all 'types' + fooQtile[i] - quantile(foo,probs=0.01,type=i) + yo[,i+1] - foo = fooQtile[i] + } names(yo) - c(myData,paste(qType,1:9,sep=)) yo myData qType1 qType2 qType3 qType4 qType5 qType6 qType7 qType8 qType9 1 6.402611 TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE 2 6.402611 TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE 3 6.420587 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE fooQtile [1] 6.40261 6.40261 6.40261 6.40261 6.40261 6.40261 6.40261 6.40261 6.40261 table(fooQtile) fooQtile 6.40261053520674 6.40261053520674 27 I expected the returned quantile to be either equal to or greater than the minimum observed value and that is the case for types 1-6 and 9. But for types 7 (the default) and 8, the returned quantile is less than the minimum observed value. The difference between the type (1-6,9) and type (7,8) return values and between the returned quantile and the minimum is obviously very very small. Is there any choice for 'type' that is guaranteed to return values inside the observed range? Thanks, Jenny Dr. Jennifer Bryan Assistant Professor Department of Statistics and the Michael Smith Laboratories University of British Columbia 333-6356 Agricultural Road Vancouver, BC Canada V6T 1Z2 __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] function to find coodinates in an array
See arrayIndex() in the R.utils package, e.g. X - array((2*3*4):1, dim=c(2,3,4)) idx - 1:length(X) ijk - arrayIndex(idx, dim=dim(X)) print(ijk) [,1] [,2] [,3] [1,]111 [2,]211 [3,]121 [4,]221 [5,]131 [6,]231 [7,]112 [8,]212 [9,]122 10,]222 11,]132 12,]232 13,]113 14,]213 15,]123 16,]223 17,]133 18,]233 19,]114 20,]214 21,]124 22,]224 23,]134 24,]234 /Henrik On 8/16/07, Moshe Olshansky [EMAIL PROTECTED] wrote: A not very good solution is as below: If your array's dimensions were KxMxN and the linear index is i then n - ceiling(i/(K*M)) i1 - i - (n-1)*(K*M) m - ceiling(i1/K) k - i1 - (m-1)*K and your index is (k,m,n) I am almost sure that there is a function in R which does this (it exists in Matlab). Regards, Moshe. --- Ana Conesa [EMAIL PROTECTED] wrote: Dear list, I am looking for a function/way to get the array coordinates of given elements in an array. What I mean is the following: - Let X be a 3D array - I find the ordering of the elements of X by ord - order(X) (this returns me a vector) - I now want to find the x,y,z coordinates of each element of ord Can anyone help me? Thanks! Ana __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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@stat.math.ethz.ch 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] reading BMP or TIFF files
See the EBImage package on Bioconductor. /Henrik On 6/7/07, Bob Meglen [EMAIL PROTECTED] wrote: I realize that this question has been asked before (2003); From: Yi-Xiong Zhou Date: Sat 22 Nov 2003 - 10:57:35 EST but I am hoping that the answer has changed. Namely, I would rather read the BMP (or TIFF) files directly instead of putting them though a separate utility for conversion as suggested by, From: Prof Brian Ripley Date: Sat 22 Nov 2003 - 15:23:33 EST Even easier is to convert .bmp to .pnm by an external utility. For example, `convert' from the ImageMagick suite (www.imagemagick.org) can do this. Thanks, Robert Meglen [EMAIL PROTECTED] [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] handling a cancelled file.choose()
See ?tryCatch. Example: Function returning NULL if cancelled: fileChoose - function(...) { pathname - NULL; tryCatch({ pathname - file.choose(); }, error = function(ex) { }) pathname; } /Henrik On 6/6/07, Ben Tupper [EMAIL PROTECTED] wrote: Hello, I have a file reading function that prompts the user with a file dialog if a filename is not provided in the argument list. It is desirable to return gracefully if the user selects Cancel, but file.choose() throws an error instead of returning something like a character. file.choose() [1] /Users/ben/ben_idl.pref file.choose() Error in file.choose() : file choice cancelled I naively planned to use nchar() to test the length, assuming cancellation would return a zero-length character. That appears to be out of the question. Are there other options available in the base package? Thanks! Ben __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Getting names of objects passed with ...
I use: foo - function(...) { args - list(...); names(args); } /Henrik On 6/1/07, Mike Meredith [EMAIL PROTECTED] wrote: Is there a tidy way to get the names of objects passed to a function via the ... argument? rbind/cbind does what I want: test.func1 - function(...) { nms - rownames(rbind(..., deparse.level=1)) print(nms) } x - some stuff second - more stuff test.func1(first=x, second) [1] first second The usual 'deparse(substitute())' doesn't do it: test.func2 - function(...) { nms - deparse(substitute(...)) print(nms) } test.func2(first=x, second) [1] x I'm using nms - rownames(rbind(...)) as a workaround, which works, but there must be a neater way! rbind/cbind are .Internal, so I can't pinch code from there. Thanks, Mike. -- View this message in context: http://www.nabble.com/Getting-names-of-objects-passed-with-%22...%22-tf3850318.html#a10906614 Sent from the R help mailing list archive at Nabble.com. __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] how to abort script with message
Hi, I think the behavior that you outline is due to the fact that you cut'n'paste the script to the R prompt, is that correct? If so, use source() instead to run your script, then stop() will do what you want. /Henrik On 5/21/07, Blew, Ted [EMAIL PROTECTED] wrote: it is desired to abort an R script with a message, returning to the R prompt, pending 'if' results, as follows: first part of script . . if (condition) { action } else { 'error' abort } . . remainder of script --- note: 'stop' aborts the current script expression but keeps running the script.[too little] 'quit' aborts the r session. [too much] thx, ted -- This e-mail and any files transmitted with it may contain privileged or confidential information. It is solely for use by the individual for whom it is intended, even if addressed incorrectly. If you received this e-mail in error, please notify the sender; do not disclose, copy, distribute, or take any action in reliance on the contents of this information; and delete it from your system. Any other use of this e-mail is prohibited. Thank you for your compliance. -- [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Size of an object in workspace
See ll() in R.oo (that is two L:s), e.g. ll() member data.class dimension objectSize 1 author character 1120 2 myfunc function NULL512 3 x matrix c(3,11)248 4 y array c(5,7,1)264 ll() is quite flexible so you can create your on functions to query objects for whatever properties you want. It can also be passed to subset(): subset(ll(), objectSize 250) member data.class dimension objectSize 2 myfunc function NULL512 4 y array c(5,7,1)264 Hope this help Henrik On 4/24/07, Horace Tso [EMAIL PROTECTED] wrote: Hi folks, Is there a function to show the size of an R object? eg. in Kbytes? Couple months ago Bendix Carstensen posted this marvelous little function lls(), which shows all objects in the current workspace by mode, class and 'size'. This is a wonderful enhancement to the build-in ls() already and I now have it sourced in my Rprofile.site at startup. The only drawback is, 'size' is just the length/dim of an object. For matrices and data frames this is good enough. But for a list, knowing how many elements in there doesn't help much. I need to know the totality of the content in a common unit, eg. byte. Thanks in advance. Horace __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Matlab import
Hi, as already mentioned, do not save MAT files in ASCII format but save to binary formats, i.e. do *not* use -ascii. Moreover, from ?readMat, you find that: From Matlab v7, _compressed_ MAT version 5 files are used by default [3]. These are not supported. Use 'save -V6' in Matlab to write a MAT file compatible with Matlab v6, that is, to write a non-compressed MAT version 5 file. Note: Do not mix up version numbers for the Matlab software and the Matlab file formats. You haven't told use what version of R you are using (neither what version of R.matlab), but from the error message I suspect you are using Matlab v7, correct? If so, try to save with save('test.mat', 'matrixM', '-ascii', '-V6') and tell us if it works. Cheers Henrik On 4/10/07, Schmitt, Corinna [EMAIL PROTECTED] wrote: Hallo, With readMat, don't use the -ascii option (which you didn't have in your first posting). I've never tried reading matlab's ascii format. In any case, readMat reads matlab's binary format. - Tom I did the saving again without 'ascii' option but the import also did not work. I get the following error message: library(R.matlab) mats - readMat(Z:/Software/R-Programme/test2.dat) Fehler in list(readMat(Z:/Software/R-Programme/test2.dat) = environment, : [2007-04-10 14:57:52] Exception: Tag type not supported: miCOMPRESSED at throw(Exception(...)) at throw.default(Tag type not supported: , tag$type) at throw(Tag type not supported: , tag$type) at readMat5DataElement(this) at readMat5(con, firstFourBytes = firstFourBytes, maxLength = maxLength) at readMat.default(Z:/Software/R-Programme/test2.dat) at readMat(Z:/Software/R-Programme/test2.dat) Any further idea, Corinna Schmitt, Corinna wrote: Hallo, I've used Henrik Bengtsson's R.matlab package several times to successfully read in matlab data files. It's normally as easy as: library(R.matlab) mats - readMat(matrixM.txt) - Tom I have imported this package, too. And tried your commands with the new txt-file as mentioned in my last mail to the mailing list. I get the following error command: mats = readMat(Z:/Software/R-Programme/test.dat) Error in if (version == 256) { : Argument hat Länge 0 Zusätzlich: Warning message: Unknown endian: . Will assume Bigendian. in: readMat5Header(this, firstFourBytes = firstFourBytes) What did I wrong? Please check my txt-file which was constructed with the matlab command save('test.dat','matrixM','-ascii') Thanks, Corinna Schmitt, Corinna wrote: Dear R-Experts, here again a question concerning matlab. With the command matrixM=[1 2 3;4 5 6] a matrix under Matlab was constructed. It was than stored with the command save('matrixM.txt','matrixM'). Now I tried to import the data in R with the help of the command Z=matrix(scan(Z:/Software/R-Programme/matrixM.txt)) An error occurred. The result should be a matrix with the entries as mentioned above. Perhaps I made already an error in matlab. Has any one got an idea how to import the data and store it in R. In R I want to make further calculations with the matrix. I just installed R.matlab but could not find an example with could help me. Thanks, Corinna MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Tue Apr 10 13:17:44 2007 �IM���3���xãc``p�b6 æÒ À å31331;çeVøÅAjYX �[n| __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- View this message in context: http://www.nabble.com/Matlab-import-tf3552511.html#a9918327 Sent from the R help mailing list archive at Nabble.com. __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- View this message in context: http://www.nabble.com/Matlab-import-tf3552511.html#a9918787 Sent from the R help mailing list archive at Nabble.com. __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide
Re: [R] erratic behavior of match()?
...and so say google [http://www.google.com/search?q=1%250.1]: 1 modulo 0.1 = 0.1, so end of discussion ;) In bit of a food coma now, but the following is interesting: r = a %% b = r = (b*a/b) %% (b*b/b) = r = b*((a/b) %% 1) modulo - function(a, b) { b * ((a/b) %% 1) } intdiv - function(a, b) { as.integer(a/b - modulo(a,b)) } a - 1 b - 0.1 modulo(a, b) [1] 0 stopifnot(all.equal(a, (a %% b) + b * (a %/% b))) stopifnot(all.equal(a, modulo(a, b) + b * intdiv(a,b))) The question is, do we gain anything at all from this, i.e. is the set of odd results larger or smaller than using a %% b, or is just a different equally sized set of numbers? ...and of course it will be a matter of how we want to define modulo - mathematically or IEEE numerically. Though, there is no such as thing as a free lunch, so probably nothing to see here... /Henrik On 4/19/07, Duncan Murdoch [EMAIL PROTECTED] wrote: On 4/19/2007 4:29 PM, Bernhard Klingenberg wrote: Thank you! Is floating point arithmetic also the reason why 1 %% 0.1 gives the surprising answer 0.1 (because 0.1 cannot be written as a fraction with denominator a power of 2, e.g. 1%%0.5 correctly gives 0). This seems to go a bit against the statement in the help for '%%', which states For real arguments, '%%' can be subject to catastrophic loss of accuracy if 'x' is much larger than 'y', and a warning is given if this is detected. I don't see the contradiction. The statement is talking about one way to get imprecise results; you may have found another. However, I'm not sure if you can blame %% in your example: the loss of precision probably came from the translation of 0.1 to the internal representation. I think 0.1 ends up a little bit larger than 0.1 after string conversion and rounding, so 1 %/% 0.1 should give 9, and 1 %% 0.1 should give something very close to 0.1, as you saw. Duncan Murdoch __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Matlab import
On 4/19/07, Spencer Graves [EMAIL PROTECTED] wrote: Have you tried 'getVariable' from Matlab? I also recently failed to get 'readMat' to work for me -- probably because I hadn't saved the files using the options Henrik suggested below. Fortunately, I was able to get something like the following to work: # Start Matlab server Matlab$startServer() # Create a Matlab client object used to communicate with Matlab matlab - Matlab() # Get max info for diagnosis setVerbose(matlab, -2) # Confirm that 'matlab' is running open(matlab) # Load the raw input data in matFile.mat into Matlab evaluate(matlab, load matFile) # Transfer it to R. varInMatfile - getVariable(matlab, variableInMatFile) # Done close(matlab) This was with Matlab 7.3.0 (R2006b) and the following versions of everything else: Yes, the MatlabServer script on the Matlab side automatically detects the version of Matlab and saves/transfers data using option -V6 if running Matlab v7 and higher. So, if this works I'm sure readMat() will work is you save with -V6. /Henrik sessionInfo() R version 2.4.1 (2006-12-18) i386-pc-mingw32 locale: LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods [7] base other attached packages: R.matlab R.oo 1.1.3 1.2.7 Hope this helps. Spencer Graves Henrik Bengtsson wrote: Hi, as already mentioned, do not save MAT files in ASCII format but save to binary formats, i.e. do *not* use -ascii. Moreover, from ?readMat, you find that: From Matlab v7, _compressed_ MAT version 5 files are used by default [3]. These are not supported. Use 'save -V6' in Matlab to write a MAT file compatible with Matlab v6, that is, to write a non-compressed MAT version 5 file. Note: Do not mix up version numbers for the Matlab software and the Matlab file formats. You haven't told use what version of R you are using (neither what version of R.matlab), but from the error message I suspect you are using Matlab v7, correct? If so, try to save with save('test.mat', 'matrixM', '-ascii', '-V6') and tell us if it works. Cheers Henrik On 4/10/07, Schmitt, Corinna [EMAIL PROTECTED] wrote: Hallo, With readMat, don't use the -ascii option (which you didn't have in your first posting). I've never tried reading matlab's ascii format. In any case, readMat reads matlab's binary format. - Tom I did the saving again without 'ascii' option but the import also did not work. I get the following error message: library(R.matlab) mats - readMat(Z:/Software/R-Programme/test2.dat) Fehler in list(readMat(Z:/Software/R-Programme/test2.dat) = environment, : [2007-04-10 14:57:52] Exception: Tag type not supported: miCOMPRESSED at throw(Exception(...)) at throw.default(Tag type not supported: , tag$type) at throw(Tag type not supported: , tag$type) at readMat5DataElement(this) at readMat5(con, firstFourBytes = firstFourBytes, maxLength = maxLength) at readMat.default(Z:/Software/R-Programme/test2.dat) at readMat(Z:/Software/R-Programme/test2.dat) Any further idea, Corinna Schmitt, Corinna wrote: Hallo, I've used Henrik Bengtsson's R.matlab package several times to successfully read in matlab data files. It's normally as easy as: library(R.matlab) mats - readMat(matrixM.txt) - Tom I have imported this package, too. And tried your commands with the new txt-file as mentioned in my last mail to the mailing list. I get the following error command: mats = readMat(Z:/Software/R-Programme/test.dat) Error in if (version == 256) { : Argument hat Länge 0 Zusätzlich: Warning message: Unknown endian: . Will assume Bigendian. in: readMat5Header(this, firstFourBytes = firstFourBytes) What did I wrong? Please check my txt-file which was constructed with the matlab command save('test.dat','matrixM','-ascii') Thanks, Corinna Schmitt, Corinna wrote: Dear R-Experts, here again a question concerning matlab. With the command matrixM=[1 2 3;4 5 6] a matrix under Matlab was constructed. It was than stored with the command save('matrixM.txt','matrixM'). Now I tried to import the data in R with the help of the command Z=matrix(scan(Z:/Software/R-Programme/matrixM.txt)) An error occurred. The result should be a matrix with the entries as mentioned above. Perhaps I made already an error in matlab. Has any one got an idea how to import the data and store it in R. In R I want to make further calculations
Re: [R] R in cron job: X problems
Try using png2() in R.utils, which immitates png() but uses bitmap() and ghostscript to create the PNG file. You need to set 'R_GSCMD' to tell R where ghostscript is located - you can use System$findGhostscript() at startup to let R try to locate ghostscript for you. /H On 4/19/07, Mark Liberman [EMAIL PROTECTED] wrote: I'd like to use an R CMD BATCH script as part of a chron job that is set up to run every hour. The trouble is that the script creates a graphical output in a file via png(), and apparently this in turn works through X. When cron invokes the job, no X server is available -- I suppose that the DISPLAY variable is not set -- and so R exits with an error message in the output file. (If I run the same script in an environment where an X server is properly available, it works as I want it to.) I tried setting DISPLAY to thecomputername:0.0 (where thecomputername is the X.Y.Z form of the computer's name as names it for ssh etc.), but that didn't work. Any advice about how to persuade the graphics subsystem to bypass X, or how to set DISPLAY in a safe way to run in a cron job? This is a linux system (a recent RedHat server system) with R 2.2.1. Thanks, Mark Liberman __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Runing R in a bash script
Or see png2() in R.utils, which imitates png() but uses bitmap(), which in turn uses postscript-to-png via ghostscript. BTW, personally I think PNGs generated via bitmap() look way better than the ones generated via png(). /Henrik On 4/17/07, Jeffrey Horner [EMAIL PROTECTED] wrote: Ulrik Stervbo wrote: Hello! I am having issues trying to plot to a ong (or jpg) when the R-code in a bash script is executed from cron. I can generate a pdf file, but when I try to write to a png, the file is created, but nothing is written. If I execute the bash script from my console, everything works file. Any ideas? In my cron I have SHELL=/bin/bash - otherwise /bin/shell is used and the folowing enery, so example is executed every minute * * * * * [path]/example.sh I am running R version 2.4.1 (2006-12-18) Here's a minimal example - two files one R-script ('example.r') and one bash-script ('example.sh') example.r # Example R-script x - c(1:10) y - x^2 png(file=example2.png) #pdf(file=example2.pdf) plot(x,y) graphics.off() example.sh #/bin/bash # # Hello world is written to exhotext every time cron executes this script echo Hello world echotext # This works, but not when executed from cron n=`R --save example.r` # using exec as in `exec R --save example.r` dosent work with cron either # This also works, but nothing is written to the png when executed from cron R --save RSCRIPT x - c(1:10) y - x^2 png(file=example2.png) #pdf(file=example2.pdf) plot(x,y) graphics.off() #dev.off() dosent work at all when executed from cron RSCRIPT The png() device requires an X server for the image rendering. You might be able to get away with exporting the DISPLAY environment variable export DISPLAY=:0.0 # try and connect to X server on display 0.0 within your script, but it will only work if the script is executed by the same user as is running the X server, *and* the X server is running at the time the script is executed. There are a handful of packages that will create a png without the presence of an X server, and I'm partial to Cairo (since I've done some work on it). You can install the latest version like this: install.packages(Cairo,,'http://rforge.net/',type='source') Cairo can also outputs nice pdf's with embedded fonts... useful if you want to embed high-quality OpenType or TrueType fonts. Best, Jeff -- http://biostat.mc.vanderbilt.edu/JeffreyHorner __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Reading a csv file row by row
Hi. On 4/6/07, Yuchen Luo [EMAIL PROTECTED] wrote: Hi, my friends. When a data file is large, loading the whole file into the memory all together is not feasible. A feasible way is to read one row, process it, store the result, and read the next row. In Fortran, by default, the 'read' command reads one line of a file, which is convenient, and when the same 'read' command is executed the next time, the next row of the same file will be read. I tried to replicate such row-by-row reading in R.I use scan( ) to do so with the skip= xxx option. It takes only seconds when the number of the rows is within 1000. However, it takes hours to read 1 rows. I think it is because every time R reads, it needs to start from the first row of the file and count xxx rows to find the row it needs to read. Therefore, it takes more time for R to locate the row it needs to read. Yes, to skip rows scan() needs to locate every single row (line feed/carriage return). The only gain you get is that it does not have to parse and store the contents of those skipped lines. One solution is to first go through the file and register the file position of the first character in every line, and then make use of this in subsequent reads. In order to do this, you have to work with an opened connection and pass that to scan instead. Rough sketch: con - file(pathname, open=r) # Scan file for first position of every line rowStarts - scanForRowStarts(con); # Skip to a certain row and read a set of lines: seek(con, where=rowStarts, origin=start, rw=r) data - scan(con, ..., skip=0, nlines=rowsPerChunk) close(con) That's the idea. The tricky part is to get scanForRowStarts() correct. After reading a line you can always query the connection for the current file position using: pos - seek(con, rw=r) so you could always iterate between readLines(con, n=1) and pos - c(pos, seek(con, rw=r)), but there might be a faster way. Cheers /Henrik Is there a solution to this problem? Your help will be highly appreciated! [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] package for Matlab
On 4/5/07, Tobias Verbeke [EMAIL PROTECTED] wrote: Schmitt, Corinna wrote: Hallo, does a package for Matlab exist in R? To read and write MAT files, there is the R.matlab package: http://cran.r-project.org/src/contrib/Descriptions/R.matlab.html This package also enables bidirectional communication between R and Matlab. A clarification: The R.matlab package is *one-directional* in the sense that you can call Matlab code from R (and get results back). You cannot call R code from Matlab using R.matlab. Cheers Henrik An alternative package with similar functionality (but not on CRAN and according to its home page not yet functional on platforms other than UNIX) is RMatlab http://www.omegahat.org/RMatlab/ To ease translation of Matlab code, there is the matlab package: http://cran.r-project.org/src/contrib/Descriptions/matlab.html HTH, Tobias If yes, where can I find it and how can I install it under R? Thanks, Corinna __ R-help@stat.math.ethz.ch 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. -- Tobias Verbeke - Consultant Business Decision Benelux Rue de la révolution 8 1000 Brussels - BELGIUM +32 499 36 33 15 [EMAIL PROTECTED] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] reading raw matrix saved with writeBin
FYI, to save data as bitmap images, see the EBImage package on Bioconductor. /H On 3/15/07, Ranjan Maitra [EMAIL PROTECTED] wrote: On Wed, 14 Mar 2007 18:45:53 -0700 (PDT) Milton Cezar Ribeiro [EMAIL PROTECTED] wrote: Dear Friends, I saved a matrix - which contans values 0 and 1 - using following command: writeBin (as.integer(mymatrix), myfile.raw, size=1). It is working fine and I can see the matrix using photoshop. But now I need read the matrices again (in fact I have a thousand of them) as matrix into R but when I try something like mat.dat-readBin (myfile.raw,size=1) I can´t access the matrix Kind regards, Miltinho __ [[alternative HTML version deleted]] Look up the help file. There is an explicit example. Basically, you need to tell the file to read in binary. In fact, I am a little surprised your first command works while writing. HTH! Ranjan __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] hpush not allowed
Hi, I've get the following on both strider and frodo: frodo{hb}: hpush -v Sorry, user hb is not allowed to execute '/usr/local/bin/hpush -v' as upush on frodo.Berkeley.EDU. Strange, because it worked when we set it up Thursday. Thxs Henrik __ R-help@stat.math.ethz.ch 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] hpush not allowed
[that one went to the wrong [EMAIL PROTECTED] sorry about that. /Henrik] On 3/2/07, Henrik Bengtsson [EMAIL PROTECTED] wrote: Hi, I've get the following on both strider and frodo: frodo{hb}: hpush -v Sorry, user hb is not allowed to execute '/usr/local/bin/hpush -v' as upush on frodo.Berkeley.EDU. Strange, because it worked when we set it up Thursday. Thxs Henrik __ R-help@stat.math.ethz.ch 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 File IO Slow?
Just an idea: Two things that can slow down save()/load() is if you save() in ASCII format or a compressed binary format. If this is your case for MYFILE, try to resave in a non-compressed binary format. See ?save for details. /HB On 3/1/07, ramzi abboud [EMAIL PROTECTED] wrote: Is R file IO slow in general or am I missing something? It takes me 5 minutes to do a load(MYFILE) where MYFILE is a 27 MB Rdata file. Is there any way to speed this up? The one idea I have is having R call a C or Perl routine, reading the file in that language, converting the data in to R objects, then sending them back into R. This is more work that I want to do, however, in loading Rdata files. Any ideas would be appreciated. Ramzi Aboud University of Rochester Need Mail bonding? __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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 directory?
Hi, I'm trying to remove/delete a directory usingR. I've tried the following with no success: % Rterm --vanilla getwd() [1] C:/Documents and Settings/hb/braju.com.R/aroma.affymetrix/test dir.create(foo) file.info(foo) size isdir mode mtime ctime atime foo0 TRUE 777 2007-02-28 14:52:10 2007-02-28 14:52:10 2007-02-28 14:52:10 # Using file.remove() res - sapply(c(foo, foo/, foo\\, ./foo, ./foo/), file.remove) res foo foo/ foo\\ ./foo ./foo/ FALSE FALSE FALSE FALSE FALSE # Using unlink() res - sapply(c(foo, foo/, foo\\, ./foo, ./foo/), unlink) res foo foo/ foo\\ ./foo ./foo/ 1 0 0 1 0 # Directory is still there file.info(foo) size isdir mode mtime ctime atime foo0 TRUE 777 2007-02-28 14:52:10 2007-02-28 14:52:10 2007-02-28 14:52:10 I've tried the above from a different directory too, i.e. setwd(C:/), with no success. Using absolute pathnames the same. This is on WinXP R v2.4.1: sessionInfo() R version 2.4.1 Patched (2007-01-13 r40470) i386-pc-mingw32 locale: LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MON ETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods [7] base Thanks Henrik __ R-help@stat.math.ethz.ch 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 directory?
Thanks! ...as the help indeed says: If 'recursive = FALSE' directories are not deleted, not even empty ones. It works; dir.create(foo) file.info(foo) size isdir mode mtime ctime atime foo0 TRUE 777 2007-02-28 15:50:33 2007-02-28 15:50:33 2007-02-28 15:50:33 print(file.remove(foo, recursive=TRUE)) [1] FALSE file.info(foo) size isdir mode mtime ctime atime foo0 TRUE 777 2007-02-28 15:50:33 2007-02-28 15:50:33 2007-02-28 15:50:33 print(unlink(foo, recursive=TRUE)) [1] 0 file.info(foo) size isdir mode mtime ctime atime foo NANA NA NA NA NA file.exists(foo) [1] FALSE /Henrik On 2/28/07, James W. MacDonald [EMAIL PROTECTED] wrote: I think you want to add a recursive = TRUE to your call to unlink(). Best, Jim Henrik Bengtsson wrote: Hi, I'm trying to remove/delete a directory usingR. I've tried the following with no success: % Rterm --vanilla getwd() [1] C:/Documents and Settings/hb/braju.com.R/aroma.affymetrix/test dir.create(foo) file.info(foo) size isdir mode mtime ctime atime foo0 TRUE 777 2007-02-28 14:52:10 2007-02-28 14:52:10 2007-02-28 14:52:10 # Using file.remove() res - sapply(c(foo, foo/, foo\\, ./foo, ./foo/), file.remove) res foo foo/ foo\\ ./foo ./foo/ FALSE FALSE FALSE FALSE FALSE # Using unlink() res - sapply(c(foo, foo/, foo\\, ./foo, ./foo/), unlink) res foo foo/ foo\\ ./foo ./foo/ 1 0 0 1 0 # Directory is still there file.info(foo) size isdir mode mtime ctime atime foo0 TRUE 777 2007-02-28 14:52:10 2007-02-28 14:52:10 2007-02-28 14:52:10 I've tried the above from a different directory too, i.e. setwd(C:/), with no success. Using absolute pathnames the same. This is on WinXP R v2.4.1: sessionInfo() R version 2.4.1 Patched (2007-01-13 r40470) i386-pc-mingw32 locale: LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MON ETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods [7] base Thanks Henrik __ R-help@stat.math.ethz.ch 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. -- James W. MacDonald University of Michigan Affymetrix and cDNA Microarray Core 1500 E Medical Center Drive Ann Arbor MI 48109 734-647-5623 ** Electronic Mail is not secure, may not be read every day, and should not be used for urgent or sensitive issues. __ R-help@stat.math.ethz.ch 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] Problem with R interface termination
Hi, this is due to the R.utils library. Interestingly, others reported this yesterday. There are three different ways to get around the problem right now: 1) Exit R so it does not call .Last() by quit(runLast=FALSE), 2) load the R.utils package and then exit via quit() as usual, or 3) remove the faulty .Last() function by rm(.Last). (Thus, you don't have kill the R process). Brief explanation: If you load the R.utils package, it will modify or create .Last() so that finalizeSession() (defined in R.utils) is called, which in turn calls so called registered hook functions allowing optional code to be evaluated whenever R exists, cf. http://tolstoy.newcastle.edu.au/R/devel/05/06/1206.html. So, if you exit R and save the session, this .Last() function will be saved to your .RData file. If you then start a new R session and load the saved .RData, that modified .Last() function will also be loaded. However, if you now try to exit R again, .Last() will be called which in turn calls finalizeSession() which is undefined since R.utils is not loaded and you will get the error that you reported. I'm testing out an updated version of R.utils (v 0.8.6), which will not cause this problem in the first place, and will fix the problem in faulty .RData. I will put in on CRAN as soon as I know it has been tested thoroughly. In the meanwhile, you can install it by: source(http://www.braju.com/R/hbLite.R;) hbLite(R.utils) To fix an old faulty .RData file, start R in the same directory, then load the updated R.utils (which will replace that faulty .Last() with a better one), and then save the session again when you exit R. When you do this you will see Warning message: 'package:R.utils' may not be available when loading, which is ok. That should fix your problems. Let me know if it works Henrik (author of R.utils) On 2/27/07, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Dear Sir, The R interface that i am currently using is R 2.4.1( in Win XP). I am not able to terminate the program by giving the q() command. Each time I pass this command, q() Error in .Last() : could not find function finalizeSession this error creeps in and it neither allows me to save my workspace nor come out of R. Therefore, whenever this happens, I am forced to end the Rgui.exe process from the task manager. Kindly help me fix this problem. Regards, Bhanu Kalyan K Bhanu Kalyan K B.Tech Final Year, CSE Tel: +91-9885238228 Alternate E-Mail: [EMAIL PROTECTED] - Need Mail bonding? [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Problem with R interface termination
For the completion of this thread; the below update was confirmed to solve the problem. /HB On 2/27/07, Henrik Bengtsson [EMAIL PROTECTED] wrote: Hi, this is due to the R.utils library. Interestingly, others reported this yesterday. There are three different ways to get around the problem right now: 1) Exit R so it does not call .Last() by quit(runLast=FALSE), 2) load the R.utils package and then exit via quit() as usual, or 3) remove the faulty .Last() function by rm(.Last). (Thus, you don't have kill the R process). Brief explanation: If you load the R.utils package, it will modify or create .Last() so that finalizeSession() (defined in R.utils) is called, which in turn calls so called registered hook functions allowing optional code to be evaluated whenever R exists, cf. http://tolstoy.newcastle.edu.au/R/devel/05/06/1206.html. So, if you exit R and save the session, this .Last() function will be saved to your .RData file. If you then start a new R session and load the saved .RData, that modified .Last() function will also be loaded. However, if you now try to exit R again, .Last() will be called which in turn calls finalizeSession() which is undefined since R.utils is not loaded and you will get the error that you reported. I'm testing out an updated version of R.utils (v 0.8.6), which will not cause this problem in the first place, and will fix the problem in faulty .RData. I will put in on CRAN as soon as I know it has been tested thoroughly. In the meanwhile, you can install it by: source(http://www.braju.com/R/hbLite.R;) hbLite(R.utils) To fix an old faulty .RData file, start R in the same directory, then load the updated R.utils (which will replace that faulty .Last() with a better one), and then save the session again when you exit R. When you do this you will see Warning message: 'package:R.utils' may not be available when loading, which is ok. That should fix your problems. Let me know if it works Henrik (author of R.utils) On 2/27/07, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Dear Sir, The R interface that i am currently using is R 2.4.1( in Win XP). I am not able to terminate the program by giving the q() command. Each time I pass this command, q() Error in .Last() : could not find function finalizeSession this error creeps in and it neither allows me to save my workspace nor come out of R. Therefore, whenever this happens, I am forced to end the Rgui.exe process from the task manager. Kindly help me fix this problem. Regards, Bhanu Kalyan K Bhanu Kalyan K B.Tech Final Year, CSE Tel: +91-9885238228 Alternate E-Mail: [EMAIL PROTECTED] - Need Mail bonding? [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] exact matching of names in attr
if (!name %in% names(attributes(dat))) { ... } /Henrik On 2/26/07, Michael Toews [EMAIL PROTECTED] wrote: In R 2.5.0 (r40806), one of the change is to allow partial matching of name in the attr function. However, how can I tell if I have an exact match or not? For example, checking to see if an object has a name attribute, then giving it one if it doesn't: dat - data.frame(x=1:10,y=rnorm(10)) if(is.null(attr(dat,name))) attr(dat,name) - Site 1 str(dat) (This example works in R 2.5) Although there is no name attribute to the data.frame, it partially matches to names, resulting in not setting the attribute. (Personally, I think this change in the attr function is not desirable, and much prefer exact matches to avoid unintentional errors). How can I tell if this is an exact match? Is there a way to force an exact match? Thanks. +mt __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] convert to binary to decimal
On 2/16/07, Jim Regetz [EMAIL PROTECTED] wrote: Roland Rau wrote: On 2/16/07, Petr Pikal [EMAIL PROTECTED] wrote: Hi slight modification of your function can be probably even quicker: fff-function(x) sum(2^(which(rev(x))-1)) :-) Petr Yes, your function is slightly but consistently faster than my suggestion. But my tests show still Bert Gunter's function to be far ahead of the rest. Mere trifling at this point, but here's a tweak that yields slightly faster performance on my system (with a caveat): # Bert's original function bert.gunter - function(x) { sum(x * 2^(rev(seq_along(x)) - 1)) } # A slightly modified function dead.horse - function(x) { sum( 2^(rev(seq_along(x))-1)[x] ) } set.seed(1) huge.list - replicate(2, sample(c(TRUE,FALSE), 20, replace=TRUE), simplify=FALSE) horse.time - replicate(15, system.time(lapply(huge.list, dead.horse))) bert.time - replicate(15, system.time(lapply(huge.list, bert.gunter))) # Print mean times (exclude first 2 to improve consistency) rowMeans(bert.time[, -(1:2)]) [1] 0.618600 0.000867 0.621000 0.00 0.00 rowMeans(horse.time[, -(1:2)]) [1] 0.580286 0.000571 0.582143 0.00 0.00 Hope no one comes along to beat this function ;-) Why not? ;) jumpy.roo - function(x) { sum(2^.subset((length(x)-1):0, x)) } horse.time - replicate(15, system.time(lapply(huge.list, dead.horse))) bert.time - replicate(15, system.time(lapply(huge.list, bert.gunter))) roo.time - replicate(15, system.time(lapply(huge.list, jumpy.roo))) rowMeans(bert.time[, -(1:2)]) [1] 0.6169231 0.000 0.6176923NANA rowMeans(horse.time[, -(1:2)]) [1] 0.604615385 0.001538462 0.603846154 NA NA rowMeans(roo.time[, -(1:2)]) [1] 0.2030769 0.000 0.2092308NANA You can push it further if you allow: jumpy.redroo - function(x) .Internal(sum(2^.subset((length(x)-1):0, x))) redroo.time - replicate(15, system.time(lapply(huge.list, jumpy.redroo))) rowMeans(redroo.time[, -(1:2)]) [1] 0.1653846 0.000 0.1646154NANA which is 3-4 faster than bert.gunter. Cheers Henrik Incidentally, I generated huge.list by randomly sampling TRUE and FALSE values with equal probability. I believe this matches what Roland did, and it seems quite reasonable given that the vectors are meant to represent binary numbers. But FWIW, as the vectors get more densely populated with TRUE values, dead.horse() loses its advantage. In the limit, if all values are TRUE, Bert's multiplication is slightly faster than logical indexing. Fun on a Friday... Cheers, Jim -- James Regetz, Ph.D. Scientific Programmer/Analyst National Center for Ecological Analysis Synthesis 735 State St, Suite 300 Santa Barbara, CA 93101 __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with tryCatch
Note that the error catch is calling your locally defined function. Like anywhere in R, if you assign something to a variable inside a function, it only applies there and not outside. The quick a dirty fix is to do: err - c(err, er) /H On 2/15/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, Please, stay with me. there is a problem with the way tryCatch processes statements and that is exactly what the help file does not describe at all. I am trying catch=function(vec){ ans=NULL;err=NULL; for (i in vec) { tryCatch({ source(i); ans=c(ans,i); cat(ans, from try); }, error=function(er){ cat(i, from catch\n); err=c(err,i); } ) } ret=list(ans=ans,err=err) ret } v=c(gdhfdh,hdhdfjh) #non-existent files ret=catch(v) # err is NULL and none of the statements in that block is executed ?? below is a Java example that executes the catch block as it should. How can I achieve the same in R? *** import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Vector; public class ReadFiles { public static void main(String[] args) { String[] files={asdf,qwert}; Vector err=new Vector(); FileReader inputStream = null; for (int j=0;j2;j++){ try { inputStream = new FileReader(files[j]); int c; while ((c = inputStream.read()) != -1) {} } catch(IOException e){ err.add(j,files[j]); // this statement executes! } finally { if (inputStream != null) { inputStream.close(); // IO not encapsulated here, but declared in main throws. pls ignore since source(arg) in R takes care of closing. } } } for (Object j:err){ System.out.println(j); } } } Henrik Bengtsson wrote: To be more precise, put the tryCatch() only around the code causing the problem, i.e. around source(). /H On 2/13/07, Henrik Bengtsson [EMAIL PROTECTED] wrote: Put the for loop outside the tryCatch(). /H On 2/13/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, thank you for the reference. Can you please tell me why the following does not work? vec=c(hdfhjfd,jdhfhjfg)# non-existent file names catch=function(vec){ tryCatch({ ans =NULL;err=NULL; for (i in vec) { source(i) ans=c(ans,i) } }, interrupt=function(ex){print(ex)}, error=function(er){ print(er) cat(i,\n) err=c(err,i) }, finally={ cat(finish) } ) #tryCatch } catch(vec) # throws an error after the first file and stops there while I want it to go through the list and accumulate the nonexistent filenames in err. Thank you Stephen Henrik Bengtsson wrote: Hi, google R tryCatch example and you'll find: http://www.maths.lth.se/help/R/ExceptionHandlingInR/ Hope this helps Henrik On 2/13/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, I had looked at tryCatch before posting the question and asked the question because the help file was not adequate for me. Could you pls provide a sample code of try{ try code} catch(error){catch code} let's say you have a vector of local file names and want to source them encapsulating in a tryCatch to avoid the skipping of all good file names after a bad file name. thank you stephen Henrik Bengtsson wrote: See ?tryCatch. /Henrik On 2/12/07, Stephen Bond [EMAIL PROTECTED] wrote: Could smb please help with try-catch encapsulating a function for downloading. Let's say I have a character vector of symbols and want to download each one and surround by try and catch to be safe # get.hist.quote() is in library(tseries), but the question does not depend on it, I could be sourcing local files instead ans=null;error=null; for ( sym in sym.vec){ try(ans=cbind(ans,get.hist.quote(sym,start=start))) #accumulate in a zoo matrix catch(theurlerror){error=c(error,sym)} #accumulate failed symbols } I know the code above does not work, but it conveys the idea. tryCatch help page says it is similar to Java try-catch, but I know how to do a try-catch in Java and still can't do it in R. Thank you very much. stephen __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code
Re: [R] help with tryCatch
Hi, google R tryCatch example and you'll find: http://www.maths.lth.se/help/R/ExceptionHandlingInR/ Hope this helps Henrik On 2/13/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, I had looked at tryCatch before posting the question and asked the question because the help file was not adequate for me. Could you pls provide a sample code of try{ try code} catch(error){catch code} let's say you have a vector of local file names and want to source them encapsulating in a tryCatch to avoid the skipping of all good file names after a bad file name. thank you stephen Henrik Bengtsson wrote: See ?tryCatch. /Henrik On 2/12/07, Stephen Bond [EMAIL PROTECTED] wrote: Could smb please help with try-catch encapsulating a function for downloading. Let's say I have a character vector of symbols and want to download each one and surround by try and catch to be safe # get.hist.quote() is in library(tseries), but the question does not depend on it, I could be sourcing local files instead ans=null;error=null; for ( sym in sym.vec){ try(ans=cbind(ans,get.hist.quote(sym,start=start))) #accumulate in a zoo matrix catch(theurlerror){error=c(error,sym)} #accumulate failed symbols } I know the code above does not work, but it conveys the idea. tryCatch help page says it is similar to Java try-catch, but I know how to do a try-catch in Java and still can't do it in R. Thank you very much. stephen __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with tryCatch
Put the for loop outside the tryCatch(). /H On 2/13/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, thank you for the reference. Can you please tell me why the following does not work? vec=c(hdfhjfd,jdhfhjfg)# non-existent file names catch=function(vec){ tryCatch({ ans =NULL;err=NULL; for (i in vec) { source(i) ans=c(ans,i) } }, interrupt=function(ex){print(ex)}, error=function(er){ print(er) cat(i,\n) err=c(err,i) }, finally={ cat(finish) } ) #tryCatch } catch(vec) # throws an error after the first file and stops there while I want it to go through the list and accumulate the nonexistent filenames in err. Thank you Stephen Henrik Bengtsson wrote: Hi, google R tryCatch example and you'll find: http://www.maths.lth.se/help/R/ExceptionHandlingInR/ Hope this helps Henrik On 2/13/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, I had looked at tryCatch before posting the question and asked the question because the help file was not adequate for me. Could you pls provide a sample code of try{ try code} catch(error){catch code} let's say you have a vector of local file names and want to source them encapsulating in a tryCatch to avoid the skipping of all good file names after a bad file name. thank you stephen Henrik Bengtsson wrote: See ?tryCatch. /Henrik On 2/12/07, Stephen Bond [EMAIL PROTECTED] wrote: Could smb please help with try-catch encapsulating a function for downloading. Let's say I have a character vector of symbols and want to download each one and surround by try and catch to be safe # get.hist.quote() is in library(tseries), but the question does not depend on it, I could be sourcing local files instead ans=null;error=null; for ( sym in sym.vec){ try(ans=cbind(ans,get.hist.quote(sym,start=start))) #accumulate in a zoo matrix catch(theurlerror){error=c(error,sym)} #accumulate failed symbols } I know the code above does not work, but it conveys the idea. tryCatch help page says it is similar to Java try-catch, but I know how to do a try-catch in Java and still can't do it in R. Thank you very much. stephen __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with tryCatch
To be more precise, put the tryCatch() only around the code causing the problem, i.e. around source(). /H On 2/13/07, Henrik Bengtsson [EMAIL PROTECTED] wrote: Put the for loop outside the tryCatch(). /H On 2/13/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, thank you for the reference. Can you please tell me why the following does not work? vec=c(hdfhjfd,jdhfhjfg)# non-existent file names catch=function(vec){ tryCatch({ ans =NULL;err=NULL; for (i in vec) { source(i) ans=c(ans,i) } }, interrupt=function(ex){print(ex)}, error=function(er){ print(er) cat(i,\n) err=c(err,i) }, finally={ cat(finish) } ) #tryCatch } catch(vec) # throws an error after the first file and stops there while I want it to go through the list and accumulate the nonexistent filenames in err. Thank you Stephen Henrik Bengtsson wrote: Hi, google R tryCatch example and you'll find: http://www.maths.lth.se/help/R/ExceptionHandlingInR/ Hope this helps Henrik On 2/13/07, Stephen Bond [EMAIL PROTECTED] wrote: Henrik, I had looked at tryCatch before posting the question and asked the question because the help file was not adequate for me. Could you pls provide a sample code of try{ try code} catch(error){catch code} let's say you have a vector of local file names and want to source them encapsulating in a tryCatch to avoid the skipping of all good file names after a bad file name. thank you stephen Henrik Bengtsson wrote: See ?tryCatch. /Henrik On 2/12/07, Stephen Bond [EMAIL PROTECTED] wrote: Could smb please help with try-catch encapsulating a function for downloading. Let's say I have a character vector of symbols and want to download each one and surround by try and catch to be safe # get.hist.quote() is in library(tseries), but the question does not depend on it, I could be sourcing local files instead ans=null;error=null; for ( sym in sym.vec){ try(ans=cbind(ans,get.hist.quote(sym,start=start))) #accumulate in a zoo matrix catch(theurlerror){error=c(error,sym)} #accumulate failed symbols } I know the code above does not work, but it conveys the idea. tryCatch help page says it is similar to Java try-catch, but I know how to do a try-catch in Java and still can't do it in R. Thank you very much. stephen __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with tryCatch
See ?tryCatch. /Henrik On 2/12/07, Stephen Bond [EMAIL PROTECTED] wrote: Could smb please help with try-catch encapsulating a function for downloading. Let's say I have a character vector of symbols and want to download each one and surround by try and catch to be safe # get.hist.quote() is in library(tseries), but the question does not depend on it, I could be sourcing local files instead ans=null;error=null; for ( sym in sym.vec){ try(ans=cbind(ans,get.hist.quote(sym,start=start))) #accumulate in a zoo matrix catch(theurlerror){error=c(error,sym)} #accumulate failed symbols } I know the code above does not work, but it conveys the idea. tryCatch help page says it is similar to Java try-catch, but I know how to do a try-catch in Java and still can't do it in R. Thank you very much. stephen __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] reading very large files
Hi. General idea: 1. Open your file as a connection, i.e. con - file(pathname, open=r) 2. Generate a row to (file offset, row length) map of your text file, i.e. a numeric vector 'fileOffsets' and 'rowLengths'. Use readBin() for this. You build this up as you go by reading the file in chunks meaning you can handles files of any size. You can store this lookup map to file for your future R sessions. 3. Sample a set of rows r = (r1, r2, ..., rR), i.e. rows = sample(length(fileOffsets)). 4. Look up the file offsets and row lengths for these rows, i.e. offsets = fileOffsets[rows]. lengths = rowLengths[rows]. 5. In case your subset of rows is not ordered, it is wise to order them first to speed up things. If order is important, keep track of the ordering and re-order them at then end. 6. For each row r, use seek(con=con, where=offsets[r]) to jump to the start of the row. Use readBin(..., n=lengths[r]) to read the data. 7. Repeat from (3). /Henrik On 2/2/07, juli g. pausas [EMAIL PROTECTED] wrote: Hi all, I have a large file (1.8 GB) with 900,000 lines that I would like to read. Each line is a string characters. Specifically I would like to randomly select 3000 lines. For smaller files, what I'm doing is: trs - scan(myfile, what= character(), sep = \n) trs- trs[sample(length(trs), 3000)] And this works OK; however my computer seems not able to handle the 1.8 G file. I thought of an alternative way that not require to read the whole file: sel - sample(1:90, 3000) for (i in 1:3000) { un - scan(myfile, what= character(), sep = \n, skip=sel[i], nlines=1) write(un, myfile_short, append=TRUE) } This works on my computer; however it is extremely slow; it read one line each time. It is been running for 25 hours and I think it has done less than half of the file (Yes, probably I do not have a very good computer and I'm working under Windows ...). So my question is: do you know any other faster way to do this? Thanks in advance Juli -- http://www.ceam.es/pausas [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] reading very large files
Forgot to say, in your script you're reading the rows unordered meaning you're jumping around in the file and there is no way the hardware or the file caching system can optimize that. I'm pretty sure you would see a substantial speedup if you did: sel - sort(sel); /H On 2/2/07, Henrik Bengtsson [EMAIL PROTECTED] wrote: Hi. General idea: 1. Open your file as a connection, i.e. con - file(pathname, open=r) 2. Generate a row to (file offset, row length) map of your text file, i.e. a numeric vector 'fileOffsets' and 'rowLengths'. Use readBin() for this. You build this up as you go by reading the file in chunks meaning you can handles files of any size. You can store this lookup map to file for your future R sessions. 3. Sample a set of rows r = (r1, r2, ..., rR), i.e. rows = sample(length(fileOffsets)). 4. Look up the file offsets and row lengths for these rows, i.e. offsets = fileOffsets[rows]. lengths = rowLengths[rows]. 5. In case your subset of rows is not ordered, it is wise to order them first to speed up things. If order is important, keep track of the ordering and re-order them at then end. 6. For each row r, use seek(con=con, where=offsets[r]) to jump to the start of the row. Use readBin(..., n=lengths[r]) to read the data. 7. Repeat from (3). /Henrik On 2/2/07, juli g. pausas [EMAIL PROTECTED] wrote: Hi all, I have a large file (1.8 GB) with 900,000 lines that I would like to read. Each line is a string characters. Specifically I would like to randomly select 3000 lines. For smaller files, what I'm doing is: trs - scan(myfile, what= character(), sep = \n) trs- trs[sample(length(trs), 3000)] And this works OK; however my computer seems not able to handle the 1.8 G file. I thought of an alternative way that not require to read the whole file: sel - sample(1:90, 3000) for (i in 1:3000) { un - scan(myfile, what= character(), sep = \n, skip=sel[i], nlines=1) write(un, myfile_short, append=TRUE) } This works on my computer; however it is extremely slow; it read one line each time. It is been running for 25 hours and I think it has done less than half of the file (Yes, probably I do not have a very good computer and I'm working under Windows ...). So my question is: do you know any other faster way to do this? Thanks in advance Juli -- http://www.ceam.es/pausas [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Need to fit a regression line using orthogonal residuals
The iwpca() in Bioconductor package aroma.light takes a matrix of column vectors and fits an R-dimensional hyperplane using iterative re-weighted PCA. From ?iwpca.matrix: Arguments: X N-times-K matrix where N is the number of observations and K is the number of dimensions. Details: This method uses weighted principal component analysis (WPCA) to fit a R-dimensional hyperplane through the data with initial internal weights all equal. At each iteration the internal weights are recalculated based on the residuals. If method==L1, the internal weights are 1 / sum(abs(r) + reps). This is the same as method=function(r) 1/sum(abs(r)+reps). The residuals are orthogonal Euclidean distance of the principal components R,R+1,...,K. In each iteration before doing WPCA, the internal weighted are multiplied by the weights given by argument w, if specified. Thus, in your case you want to do: X - cbind(x,y) fit - iwpca(X) There are different ways of robustifying the estimate, cf. argument 'method'. For heteroscedastic noise, fitting in L1 is convenient since there is no bandwidth parameter. Hope this helps Henrik On 1/30/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Jonathon Kopecky asks: -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Jonathon Kopecky Sent: Tuesday, 30 January 2007 5:52 AM To: r-help@stat.math.ethz.ch Subject: [R] Need to fit a regression line using orthogonal residuals I'm trying to fit a simple linear regression of just Y ~ X, but both X and Y are noisy. Thus instead of fitting a standard linear model minimizing vertical residuals, I would like to minimize orthogonal/perpendicular residuals. I have tried searching the R-packages, but have not found anything that seems suitable. I'm not sure what these types of residuals are typically called (they seem to have many different names), so that may be my trouble. I do not want to use Principal Components Analysis (as was answered to a previous questioner a few years ago), I just want to minimize the combined noise of my two variables. Is there a way for me to do this in R? [WNV] There's always a way if you are prepared to program it. Your question is a bit like asking Is there a way to do this in Fortran? The most direct way to do it is to define a function that gives you the sum of the perpendicular distances and minimise it using, say, optim(). E.g. ppdis - function(b, x, y) sum((y - b[1] - b[2]*x)^2/(1+b[2]^2)) b0 - lsfit(x, y)$coef # initial value op - optim(b0, ppdis, method = BFGS, x=x, y=y) op # now to check the results plot(x, y, asp = 1) # why 'asp = 1'?? exercise abline(b0, col = red) abline(op$par, col = blue) There are a couple of things about this you should be aware of, though First, this is just a fiddly way of finding the first principal component, so your desire not to use Principal Component Analysis is somewhat thwarted, as it must be. Second, the result is sensitive to scale - if you change the scales of either x or y, e.g. from lbs to kilograms, the answer is different. This also means that unless your measurement units for x and y are comparable it's hard to see how the result can make much sense. A related issue is that you have to take some care when plotting the result or orthogonal distances will not appear to be orthogonal. Third, the resulting line is not optimal for either predicting y for a new x or x from a new y. It's hard to see why it is ever of much interest. Bill Venables. Jonathon Kopecky University of Michigan __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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@stat.math.ethz.ch 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.oo Destructors
Hi, I'm about the head out of the office next 48 hours, but the short answer is to override the finalize() method in your subclass of Object. This will be called when R garbage collects the object. From ?finalize.Object: setConstructorS3(MyClass, function() { extend(Object(), MyClass) }) setMethodS3(finalize, MyClass, function(this) { cat(as.character(this), is about to be removed from the memory!\n) }) o - MyClass() o - MyClass() o - MyClass() o - MyClass() gc() ## Not run: MyClass: 0x31543776 is about to be removed from the memory! MyClass: 0x31772572 is about to be removed from the memory! MyClass: 0x32553244 is about to be removed from the memory! used (Mb) gc trigger (Mb) max used (Mb) Ncells 246049 6.6 407500 10.9 35 9.4 Vcells 132538 1.1 786432 6.0 404358 3.1 rm(o) gc() MyClass: 0x31424196 is about to be removed from the memory! used (Mb) gc trigger (Mb) max used (Mb) Ncells 246782 6.6 467875 12.5 354145 9.5 Vcells 110362 0.9 786432 6.0 404358 3.1 Hope this helps Henrik On 1/18/07, Feng, Ken [CIB-EQTY] [EMAIL PROTECTED] wrote: Has anyone figured out how to create a destructor in R.oo? How I'd like to use it: I have an object which opens a connection thru RODBC (held as a private member) It would be nice if the connection closes automatically (inside the destructor) when an object gets gc()'ed. Thanks in advance. Regards, Ken BTW, a BIG thanks to Henrik Bengtsson for creating the R.oo package! Lucky for me as I am not smart enough to use S4... __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] [[ gotcha
To create a empty list do: B - list() /H On 1/16/07, Robin Hankin [EMAIL PROTECTED] wrote: The following gotcha caught me off-guard just now. I have two matrices, a and b: a - matrix(1,3,3) b - matrix(1,1,1) (note that both a and b are matrices). I want them in a list: B - NULL B[[1]] - a B[[2]] - b B [[1]] [,1] [,2] [,3] [1,]111 [2,]111 [3,]111 [[2]] [,1] [1,]1 This is fine. But swapping a and b over does not behave as desired: B - NULL B[[1]] - b B[[2]] - a Error in B[[2]] - a : more elements supplied than there are to replace The error is given because after B[[1]] - a, the variable B is just a scalar and not a matrix (why is this?) What's the bulletproof method for assigning matrices to a list (whose length is not known at runtime)? -- Robin Hankin Uncertainty Analyst National Oceanography Centre, Southampton European Way, Southampton SO14 3ZH, UK tel 023-8059-7743 __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Speeding things up
First, since you only update the 'ddtd' conditioned on 'value', you should be able to vectorize removing the loop. I let you figure out how to do that yourself. Second, you apply the $ operator multiple times in the loop that will definitely add some overhead. It should be faster to extract 'value' and 'ddtd' and work with those instead. /Henrik On 1/8/07, Benjamin Dickgiesser [EMAIL PROTECTED] wrote: Hi, is it possible to do this operation faster? I am going over 35k data entries and this takes quite some time. for(cnt in 2:length(sdata$date)) { if(sdata$value[cnt] sdata$value[cnt - 1]) { sdata$ddtd[cnt] - sdata$ddtd[cnt - 1] + sdata$value[cnt - 1] - sdata$value[cnt] } else sdata$ddtd[cnt] - 0 } return(sdata) Thank you, Benjamin __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] A question about R environment
sourceTo() in R.utils will allow you to source() a file into an environment. /Henrik On 1/9/07, Gabor Grothendieck [EMAIL PROTECTED] wrote: Try this: e - new.env() e$f - function(x)x attach(e) search() [1] .GlobalEnve package:stats [4] package:graphics package:grDevices package:utils [7] package:datasets package:methods Autoloads [10] package:base f function(x)x On 1/8/07, Tong Wang [EMAIL PROTECTED] wrote: Hi all, I created environment mytoolbox by : mytoolbox - new.env(parent=baseenv()) Is there anyway I put it in the search path ? If you need some background : In a project, I often write some small functions, and load them into my workspace directly, so when I list the objects with ls(), it looks pretty messy. So I am wondering if it is possible to creat an environment, and put these tools into this environment. For example, I have functionsfun1(), fun2() .. and creat an environment mytoolbox which contains all these functions. And it should be somewhere in the search path: .GlobalEnvmytoolbox package:methods __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Evaluating Entire Matlab code at a time
This is very odd, but maybe 'cd' is not a command on your Windows Matlab installation. I tried the same code on a Unix installation (I don't have access to Matlab for Windows but others have been using R.matlab there successfully). Find out what the command for getting the current directory in your Matlab version is and use that instead. You could also troubleshoot by this: 1. Start Matlab using Matlab$startServer(minimize=FALSE) 2. Setup the Matlab connection from R and close it with close(matlab). 3. Go to the Matlab windows and try the commands that failed for you when called from R. This will give you a hint. Remember, there is nothing magic going on. Think about the R Matlab connection as R is typing the Matlab commands for you; anything you can do in that Matlab windows which you did close(matlab) on you can do with evaluate(matlab, ...) - before closing it that is. /Henrik On 12/30/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Dear Mr. Bengtsson, I worked on the code you sent. But, I dont think it is responding either. Kindly verify. evaluate(matlab, pwd=cd();); Sending expression on the Matlab server to be evaluated...: 'pwd=cd();' Received an 'MatlabException' reply (-1) from the Matlab server: 'Error: Expected a variable, function, or constant, found ).' Error in list(evaluate(matlab, pwd=cd();) = environment, evaluate.Matlab(matlab, pwd=cd();) = environment, : [2006-12-30 15:08:34] Exception: MatlabException: Error: Expected a variable, function, or constant, found ). at throw(Exception(...)) at throw.default(MatlabException: , lasterr) at throw(MatlabException: , lasterr) at readResult.Matlab(this) at readResult(this) at evaluate.Matlab(matlab, pwd=cd();) at evaluate(matlab, pwd=cd();) pwd - getVariable(matlab, pwd)$pwd; Retrieving variables from the Matlab server: 'pwd' Sending expression on the Matlab server to be evaluated...: 'variables = {'pwd'};' Received an 'OK' reply (0) from the Matlab server. Evaluated expression on the Matlab server with return code 0. Asks the Matlab server to send variables via the local file system... Error in readChar(con = con, nchars = nbrOfBytes) : invalid value for 'nchar' print(pwd); Error in print(pwd) : object pwd not found evaluate(matlab, files=dir();) Sending expression on the Matlab server to be evaluated...: 'files=dir();' Error in readChar(con = con, nchars = nbrOfBytes) : invalid value for 'nchar' Kindly verify and let me know the solution. Regards, Bhanu Kalyan K Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __ R-help@stat.math.ethz.ch 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] Failure loading library into second R 2.3.1 session on Windows XP
Hi, it sounds like you mixing up the words install and load. Basically, you only have to *install* a package once on your computer, but have to load it for every R session which you are going to use it in. So, in your case install it once, using either install.packages(corpcor) or the corresponding menu in RGui (on Windows), and then use library(corpcor) every time you want to *load* the package (typically once per R session). See An Introduction to R for further explainations. Details: When you try to install a package a second time the previous installation is overwritten. However, if another R session has the same package loaded, some of the files of the package might be looked, and won't be released until the package is unloaded or you quit the R session. Thus, when you try to install the package a second time (in another R session or even the same) it will not work. This is expected. Hope this helps Henrik On 12/30/06, Talbot Katz [EMAIL PROTECTED] wrote: Hi Uwe. Thank you so much for responding! I guess I wasn't entirely clear about the problem. If I make the mistake of trying to install a package from CRAN in a second session after I've already installed it in a previous session, it won't install in the second session, and even if I close the second session and open a subsequent newer session, it won't install in that one either. At least, I can't figure out how to do it, because it's no longer in the Load packages... menu, and if I load it from CRAN, I get that funny error message: Warning: cannot remove prior installation of package 'corpcor' Now, after having gone through this, I know enough not to reload a package from CRAN. But it appears that the only ways to solve the problem, if it occurs, are pretty drastic, either reboot the machine (which is what I did) or reinstall R (which seems to be what you're suggesting?). I was hoping that there might be a better alternative, or at least that the development team might look into this issue for future releases. This doesn't affect every package, but I've seen it in the first two packages I tried it with. -- TMK -- 212-460-5430home 917-656-5351cell From: Uwe Ligges [EMAIL PROTECTED] To: Talbot Katz [EMAIL PROTECTED] CC: r-help@stat.math.ethz.ch Subject: Re: [R] Failure loading library into second R 2.3.1 session on Windows XP Date: Fri, 29 Dec 2006 23:05:15 +0100 You can only expect that update / reinstall a ***package*** works if you have not yet loaded it into your R session. Hence close R, start it without loading the relevant package and then update/reinstall. Best, Uwe Ligges Talbot Katz wrote: Hi. I am using R 2.3.1 on Windows XP. I had installed a library package into my first session and wanted the same package in my second session, so I went out to the CRAN mirror and tried to install the package, and got the following message: * utils:::menuInstallPkgs() trying URL 'http://cran.ssds.ucdavis.edu/bin/windows/contrib/2.3/corpcor_1.4.4.zip' Content type 'application/zip' length 133068 bytes opened URL downloaded 129Kb package 'corpcor' successfully unpacked and MD5 sums checked Warning: cannot remove prior installation of package 'corpcor' The downloaded packages are in C:\Documents and Settings\Talbot\Local Settings\Temp\RtmplCxarb\downloaded_packages updating HTML package descriptions library(corpcor) Error in library(corpcor) : there is no package called 'corpcor' * After rebooting my machine, I dug into this a little further. Upon installing a package from a CRAN mirror, it seems to stay on my hard drive, and I can load it in subsequent sessions from the Load package... menu without going back to get it from a CRAN mirror. However, if I do happen to retrieve it again from a CRAN mirror, it appears that may corrupt the version that was saved, and it no longer will be available from the Load package... menu. A reboot and re-retrieval of the package makes it available again; I don't know whether there's any less drastic solution. This behavior doesn't occur with every package, but I have experienced it with two different packages (corpcor and copula), so there seems to be something going on. I didn't see anything in the FAQ page about this, I wonder if anyone can tell me more about this issue. Thanks! -- TMK -- 212-460-5430 home 917-656-5351 cell __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch mailing list
Re: [R] Evaluating Entire Matlab code at a time
Hi. On 12/30/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Dear Mr.Bengtsson, The steps you have suggested are working for single lines of matlab statements. But, as i mentioned earlier, If i want to see the output of an entire matlab code (say swissroll.m) then you suggested me to do res - evaluate(matlab, swissroll). When i did this the output looks something like: res - evaluate(matlab, swissroll) Sending expression on the Matlab server to be evaluated...: 'swissroll' Received an 'MatlabException' reply (-1) from the Matlab server: 'Undefined function or variable 'lle'.' Error in list(evaluate(matlab, swissroll) = environment, evaluate.Matlab(matlab, swissroll) = environment, : [2006-12-30 11:58:32] Exception: MatlabException: Undefined function or variable 'lle'. at throw(Exception(...)) at throw.default(MatlabException: , lasterr) at throw(MatlabException: , lasterr) at readResult.Matlab(this) at readResult(this) at evaluate.Matlab(matlab, swissroll) at evaluate(matlab, swissroll) // Here another matlab window titled Figure no.1 (corresponding to the actual matlab output of swissroll.m) opened, but the window is blank. No output is being displayed. However, when i used the same command for another matlab code, kMeansCluster.m, the warnings/Exceptions generated are similar to that os swissroll.m. Here is the output: res - evaluate(matlab, kMeansCluster;) Sending expression on the Matlab server to be evaluated...: 'kMeansCluster;' Received an 'MatlabException' reply (-1) from the Matlab server: 'Undefined function or variable 'kMeansCluster'.' Error in list(evaluate(matlab, kMeansCluster;) = environment, evaluate.Matlab(matlab, kMeansCluster;) = environment, : [2006-12-30 11:56:34] Exception: MatlabException: Undefined function or variable 'kMeansCluster'. at throw(Exception(...)) at throw.default(MatlabException: , lasterr) at throw(MatlabException: , lasterr) at readResult.Matlab(this) at readResult(this) at evaluate.Matlab(matlab, kMeansCluster;) at evaluate(matlab, kMeansCluster;) The warnings generated are almost similar for those two different matlab codes. So i feel that the problem lies with the R and not the code. What do u suggest? how to deal with this? To me this looks like Matlab can't find those commands, and then it has nothing to with R. Make sure your Matlab scripts are available in the Matlab path or in the working directory of Matlab. You check the working directory of Matlab with: evaluate(matlab, pwd=cd();); pwd - getVariable(matlab, pwd)$pwd; print(pwd); Check to see if your scripts are in the working directory: evaluate(matlab, files=dir();) files - getVariable(matlab, files)$files unlist(files[name,,]) If not, you have to update your Matlab path or change the working directory. Hope this helps Henrik Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __ R-help@stat.math.ethz.ch 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] Query regarding linking R with Matlab
On 12/28/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Respected Sir, It worked. open(matlab) [1] TRUE Good. But however, the 'evaluate' function is not responding. When i give the command as: res - evaluate(matlab, A=1+2;, B=ones(2,20);) The R interface is not returning any value though i wait for 3-4 minutes. This example should respond more or less instantaneously. Same is the case with close(matlab) This is not closing the matlab window, neither it is throwing any warning. It is just asking me to wait but finally outputs no result. I am forced to stop the current computation. Ok, let's turn on all output you can in order to troubleshoot this. Make sure to do: setVerbose(matlab, -2) before those non-responding calls. You may also start the Matlab server in a non-minimized window by calling: Matlab$startServer(minimize=FALSE) This will allow you to see what the Matlab server is doing. What do you get? /H PS. Normally the above should work out of the box; I'm not sure why you experience all these problems. DS. Now please guide me as to how to evaluate some matlab expressions. Thanking you, Regards Bhanu Kalyan K Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __ R-help@stat.math.ethz.ch 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] Query regarding linking R with Matlab
[Forwarding to r-help for completeness. /Henrik] -- Forwarded message -- From: Henrik Bengtsson [EMAIL PROTECTED] Date: Dec 28, 2006 9:45 PM Subject: Re: [R] Query regarding linking R with Matlab To: [EMAIL PROTECTED] Hi. On 12/28/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Respected Sir, I am sorry that i forgot to 'setVerbose'. Now when that is set, The result is: Matlab$startServer(minimize=FALSE) [1] 0 matlab - Matlab(host=localhost) open(matlab) [1] TRUE setVerbose(matlab, -2) res - evaluate(matlab, A=1+2;, B=ones(2,20);) Sending expression on the Matlab server to be evaluated...: 'A=1+2; B=ones(2,20);' Received an 'OK' reply (0) from the Matlab server. Evaluated expression on the Matlab server with return code 0. res NULL close(matlab) Closing connection to host 'localhost' (port )... Received an 'OK' reply (0) from the Matlab server. Closing connection to host 'localhost' (port )...done What should res object contain finally when we are doing res - evaluate(matlab, A=1+2;, B=ones(2,20);) ?? The return value of evaluate() is NULL when successful (I noticed the help is saying '0'; I've corrected that for the next version). Anyway, 'res' contains nothing of interest. If there is any error on the Matlab side, an error is thrown in R giving you the details. What you might want to do is: data - getVariable(matlab, A) str(data) once i do close(matlab), the matlab server is shutdown, Yes, the server script is shut down, but Matlab is left running on purpose so you have a chance to continue working with the Matlab session by hand. However, when i ask for the values of A B in matlab window, the output is displayed correctly. The matlab window outputs thus: » A A = 3 » B B = Columns 1 through 17 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Columns 18 through 20 1 1 1 1 1 1 What do you interpret? That everything is now working as expected. See the example of help(Matlab) to get more ideas how to interact with Matlab from R. Cheers Henrik Kindly let me know Regards Bhanu Kalyan K Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __ R-help@stat.math.ethz.ch 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] Query regarding linking R with Matlab
Hi, It might be that R can't find Matlab; then you have to specify option 'matlab', see help(Matlab). Try also a different port. Try to add a line setVerbose(matlab, -2) to get more detailed output what is going on; matlab - Matlab(host=localhost, port=9998) setVerbose(matlab, -2) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) If you can't get it to work, send the output of the above. /Henrik On 12/27/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Respected Sir, I thank you for your concern. I have worked with the code that you have provided. But it has generated errors like: if (!open(matlab)) + throw(Matlab server is not running: waited 30 seconds.) //This command is not responding even after 30 seconds. res - evaluate(matlab, swissroll) Error in writeBin(con = con, as.integer(b), size = 1) : invalid connection vars - getVariable(matlab, c(Y, X, K, d)) Error in writeBin(con = con, as.integer(b), size = 1) : invalid connection Kindly help me with this. Regards Bhanu Kalyan K Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __ R-help@stat.math.ethz.ch 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] Query regarding linking R with Matlab
Hi. From what you tell me you manage to start Matlab in the background by calling: Matlab$startServer() but that R fails to connect to Matlab by: matlab - Matlab(host=localhost, port=9998) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) Sorry for not being explicit enough; if no port is given, Matlab$startServer() will setup up Matlab to listen to port (as explained in the help), but then you try to communicate with it via port 9998. I realize that the example might be a bit confusing since it is using port 9998 (for the purpose of illustrating the fact that you can choose another port). Either try the above with Matlab$startServer(port=9998), *or*, maybe simpler: Matlab$startServer() matlab - Matlab(host=localhost) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) Does this work for you? Henrik On 12/27/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: library(R.matlab) Loading required package: R.oo R.oo v1.2.3 (2006-09-07) successfully loaded. See ?R.oo for help. R.matlab v1.1.2 (2006-05-08) successfully loaded. See ?R.matlab for help. help(Matlab) Matlab$startServer()Loading required package: R.utils R.utils v0.8.0 (2006-08-21) successfully loaded. See ?R.utils for help. [1] 0 // Here a Matlab window opened but that window couldnot be maximized. matlab - Matlab(host=localhost, port=9998) matlab [1] Matlab: The Matlab host is 'localhost' and communication goes via port 9998. Objects are passed via the local file system (remote=FALSE). The connection to the Matlab server is closed (not opened). setVerbose(matlab, -2) open(matlab) Opens a blocked connection to host 'localhost' (port 9998)... Try #0. Try #1. Try #2. Try #3. Try #4. Try #5. Try #6. Try #7. Try #8. Try #9. Try #10. Try #11. Try #12. There were 12 warnings (use warnings() to see them) Opens a blocked connection to host 'localhost' (port 9998)...done if (!open(matlab)) + throw(Matlab server is not running: waited 30 seconds.) Opens a blocked connection to host 'localhost' (port 9998)... Try #0. Try #1. // I 'stopped' the computation here Warning message: localhost:9998 cannot be opened Opens a blocked connection to host 'localhost' (port 9998)...done This is the output obtained after running the commands. Kindly go through the above commands and help me identify the problem. Regards, Bhanu Kalyan K Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __ R-help@stat.math.ethz.ch 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.matlab question
Hi, a follow up after realizing that you might not have started the Matlab application to listen on port 9998. Try: Matlab$startServer(port=9998) and then matlab - Matlab(host=localhost, port=9998) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) Does this help? Henrik On 12/20/06, Henrik Bengtsson [EMAIL PROTECTED] wrote: Hi. On 12/20/06, Aimin Yan [EMAIL PROTECTED] wrote: Does anyone know how to solve this question about R.matlab? I am in windowsXP, my matlab is matlab 7.0.0 19920(R14) thanks, Aimin matlab - Matlab(host=localhost, port=9998) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) Error in list(throw(Matlab server is not running: waited 30 seconds.) = environment, : [2006-12-17 22:26:03] Exception: Matlab server is not running: waited 30 seconds. at throw(Exception(...)) at throw.default(Matlab server is not running: waited 30 seconds.) at throw(Matlab server is not running: waited 30 seconds.) In addition: There were 30 warnings (use warnings() to see them) warnings function (...) UseMethod(warnings) warnings() Warning messages: 1: localhost:9998 cannot be opened 2: localhost:9998 cannot be opened [snip] 30: localhost:9998 cannot be opened This could be because your firewall is blocking R from connecting to Matlab. Try a few different port numbers. I recently learned that the current default port in R.matlab might not be the best one; different port intervals are reserved for different purposes, cf. http://www.iana.org/assignments/port-numbers. That document indicates that a port number in [49152, 65535] might be better. See if this helps. Does someone else knowof a port interval that is more likely to work in general? You can also tell the Matlab object to report more details what it is trying to do by setting the verbosity threshold, i.e. setVerbose(matlab, threshold=-1); the lower the threshold the more details you'll see. Cheers Henrik __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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.matlab question
Hi. On 12/20/06, Aimin Yan [EMAIL PROTECTED] wrote: Does anyone know how to solve this question about R.matlab? I am in windowsXP, my matlab is matlab 7.0.0 19920(R14) thanks, Aimin matlab - Matlab(host=localhost, port=9998) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) Error in list(throw(Matlab server is not running: waited 30 seconds.) = environment, : [2006-12-17 22:26:03] Exception: Matlab server is not running: waited 30 seconds. at throw(Exception(...)) at throw.default(Matlab server is not running: waited 30 seconds.) at throw(Matlab server is not running: waited 30 seconds.) In addition: There were 30 warnings (use warnings() to see them) warnings function (...) UseMethod(warnings) warnings() Warning messages: 1: localhost:9998 cannot be opened 2: localhost:9998 cannot be opened [snip] 30: localhost:9998 cannot be opened This could be because your firewall is blocking R from connecting to Matlab. Try a few different port numbers. I recently learned that the current default port in R.matlab might not be the best one; different port intervals are reserved for different purposes, cf. http://www.iana.org/assignments/port-numbers. That document indicates that a port number in [49152, 65535] might be better. See if this helps. Does someone else knowof a port interval that is more likely to work in general? You can also tell the Matlab object to report more details what it is trying to do by setting the verbosity threshold, i.e. setVerbose(matlab, threshold=-1); the lower the threshold the more details you'll see. Cheers Henrik __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Query regarding linking R with Matlab
Hi. On 12/20/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Sir, I am still new to the R-matlab interfacing. I will explain you the problem statement more clearly. The following is a matlab code. (swissroll.m) = % SWISS ROLL DATASET N=2000; K=12; d=2; clf; colordef none; colormap jet; set(gcf,'Position',[200,400,620,200]); % PLOT TRUE MANIFOLD tt0 = (3*pi/2)*(1+2*[0:0.02:1]); hh = [0:0.125:1]*30; xx = (tt0.*cos(tt0))'*ones(size(hh)); yy = ones(size(tt0))'*hh; zz = (tt0.*sin(tt0))'*ones(size(hh)); cc = tt0'*ones(size(hh)); subplot(1,3,1); cla; surf(xx,yy,zz,cc); view([12 20]); grid off; axis off; hold on; lnx=-5*[3,3,3;3,-4,3]; lny=[0,0,0;32,0,0]; lnz=-5*[3,3,3;3,3,-3]; lnh=line(lnx,lny,lnz); set(lnh,'Color',[1,1,1],'LineWidth',2,'LineStyle','-','Clipping','off'); axis([-15,20,0,32,-15,15]); % GENERATE SAMPLED DATA tt = (3*pi/2)*(1+2*rand(1,N)); height = 21*rand(1,N); X = [tt.*cos(tt); height; tt.*sin(tt)]; % SCATTERPLOT OF SAMPLED DATA subplot(1,3,2); cla; scatter3(X(1,:),X(2,:),X(3,:),12,tt,'+'); view([12 20]); grid off; axis off; hold on; lnh=line(lnx,lny,lnz); set(lnh,'Color',[1,1,1],'LineWidth',2,'LineStyle','-','Clipping','off'); axis([-15,20,0,32,-15,15]); drawnow; % RUN LLE ALGORITHM Y=lle(X,K,d); % SCATTERPLOT OF EMBEDDING subplot(1,3,3); cla; scatter(Y(1,:),Y(2,:),12,tt,'+'); grid off; set(gca,'XTick',[]); set(gca,'YTick',[]); === I must write a program in R, which will call this swissroll.m file. The output (of swissroll.m) must be shown in R interface and not in matlab . Is it possible? How can i do it? Kindly bear with me as i am not very comfortable with R. Though i have read your help(Matlab) and the examples, i did not find any clear documentation regarding calling an external file in R. Please help me on this. The R.matlab package basically allows you to *evaluate* Matlab code sent from R as text strings. In addition you can transfer *data structures* between R and Matlab (in both directions). So, instead of running Matlab in one window and R in another, typing some commands in Matlab, saving data to file, moving over to R and load that data file into R etc, the R.matlab package allows you to do all that from within R. That is the main idea behind R.matlab. Thus, you cannot generate graphs in Matlab and magically expect them to be transferred to R. However, like when you run Matlab by hand you can save graphs to file, e.g. PNG or EPS files. The R.matlab interface allows you to tell Matlab to do that from within R. To run (=evaluate) your 'swissroll.m' Matlab script from R matlab - Matlab(host=localhost, port=9998) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) res - evaluate(matlab, swissroll) This will then open *Matlab* windows displaying the figures. You can import the Matlab variables of interest to R by: vars - getVariable(matlab, c(Y, X, K, d)) ...and the work with the variables in R instead, e.g. Y - vars$Y. Hope this helps Henrik regards, Bhanu Kalyan K Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] call by reference
There is no support for 'call by reference' in the S language, and this is intentionally, but you can use environments to imitate it, cf. ?environment. See also the R.oo package. /Henrik On 12/20/06, biter bilen [EMAIL PROTECTED] wrote: Can anyone help me about pass by reference of arguments in R functions? I have read about .Alias in base package however it is defunct and there is no replacement for it. Thanks in advance. __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Query regarding linking R with Matlab
Hi, what operating system are you on and what version of Matlab do you have? In general you should be able to get started with R.matlab by first installing all required packages from CRAN: install.packages(c(R.oo, R.utils, R.matlab)) Then load the package: library(R.matlab) From there just follow the example in help(Matlab): # Create a Matlab client matlab - Matlab(host=localhost, port=9998) # Connect to the Matlab server if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) # Run Matlab expressions on the Matlab server res - evaluate(matlab, A=1+2;, B=ones(2,20);) # Get Matlab variables data - getVariable(matlab, c(A, B)) cat(Received variables:\n) str(data) ... # When done, close the Matlab client, which will also shutdown # the Matlab server and the connection to it. close(matlab) Hope this helps Henrik On 12/15/06, Bhanu Kalyan.K [EMAIL PROTECTED] wrote: Thank you sir for your prompt reply. Currently i am stuck at point where I need to call an available Matlab program from an R 2.4.0 interface. How can I do this? I have downloaded the R.matlab file and also the manual in pdf. But still i am not able to get through the problem. I will be grateful to you if you can elaborate me on this. Awaiting your reply, regards, Bhanu Kalyan K Bhanu Kalyan K BTech CSE Final Year [EMAIL PROTECTED] Tel :+91-9885238228 __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __ R-help@stat.math.ethz.ch 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] Start Matlab server in R 2.4.0
Hi. On 12/18/06, Aimin Yan [EMAIL PROTECTED] wrote: In order to start matlab server in R , I using the following commands getwd() setwd(D:\R_matlab) install.packages(R.oo) install.packages(R.matlab) install.packages(R.utils) library(R.matlab) Matlab$startServer() a minimized MATLAB Command Window come out, but I can't make this window become larger. Does anyone know why? You can change this, by calling Matlab$startServer(minimize=FALSE) On Windows, Matlab is started minimized by default, because the information in that window is of no interest (except for debugging) and you cannot type anything in that window anyway. However, read further... I type Matlab$startServer() again, I get another MATLAB Command Window and I can maximize this window, From this window: I see such message: To get started, type one of these: helpwin, helpdesk, or demo. For product information, visit www.mathworks.com. Matlab v7.x or higher detected. Saving with option -V6. Added InputStreamByteWrapper to dynamic Java CLASSPATH. -- Matlab server started! -- Trying to open server socket (port )...??? Java exception occurred: java.net.BindException: Address already in use: JVM_Bind at java.net.PlainSocketImpl.socketBind(Native Method) at java.net.PlainSocketImpl.bind(Unknown Source) at java.net.ServerSocket.bind(Unknown Source) at java.net.ServerSocket.init(Unknown Source) at java.net.ServerSocket.init(Unknown Source) . Error in == MatlabServer at 113 server = ServerSocket(port); » Does anyone would like to point out what is reason for these? The reason for this is that you already started one Matlab session using (default) port . When you start the second one, the error message (from Java) says that that port is already taken. So this is expected. However, I am not sure why you can't maximize the first, but the second. Odd. However, ... I am new to R.matlab. I am not sure if this question is too silly. Before I post this question here, I did try to do google search to find answer by myself. But I didn't get point. If this question bother you too much, I am really sorry for this. You do not have to start the Matlab server explicitly like this; instead setup a Matlab object in R as illustrated in the help(R.matlab) example and the server will be started when you call open() on that object, e.g. matlab - Matlab(host=localhost, port=9998) if (!open(matlab)) throw(Matlab server is not running: waited 30 seconds.) # If you get here, you have a working R-Matlab connection BCD - matrix(rnorm(1), ncol=100) setVariable(matlab, ABCD=ABCD) # Send to Matlab data - getVariable(matlab, ABCD) # Receive from Matlab str(data) The open() call will call Matlab$startServer() for you, and on Windows it will be minimized, so in that sense there is no change. But again, there is not much for you to see there. Hope this helps Henrik Thanks, Aimin Yan __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] How do I create an object in the Global environment from a function
Please note that help(-) says: The operators '-' and '-' cause a search to made through the environment for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. Thus, if you really want to make sure to assign it to the global environment you should do: assign(b, value, envir=globalenv()) /Henrik On 12/14/06, Rainer M Krug [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Hi all, Say I have created an object b in my function myfunc - function() b - 34 myfunc - function() b - 34 - Rainer How can I make b an object in the Global environment and not just in the environment of myfunc? Thanks, Tim __ R-help@stat.math.ethz.ch 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. -- Rainer M. Krug, Dipl. Phys. (Germany), MSc Conservation Biology (UCT) Department of Conservation Ecology and Entomology University of Stellenbosch Matieland 7602 South Africa Tel:+27 - (0)72 808 2975 (w) Fax:+27 - (0)86 516 2782 Fax:+27 - (0)21 808 3304 (w) Cell: +27 - (0)83 9479 042 email: [EMAIL PROTECTED] [EMAIL PROTECTED] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] reaccessing array at a later date - trying to write it to file
Here is a simple function that allow you to load the objects stored by save() into an evironment (to avoid loading them into the global workspace): loadToEnv - function(...) { env - new.env() load(..., env=env) env } x - 1:10 save(file=foo.xdr, x, letters, R.version) objects - loadToEnv(foo.xdr) ls(env=objects) [1] letters R.version x objects$x [1] 1 2 3 4 5 6 7 8 9 10 and so on. /Henrik On 11/24/06, Jenny Barnes [EMAIL PROTECTED] wrote: Thank you Barry for your time in responding! I think that will really help - the difference between attach and load were not clear to me before your reply! Also I did not know about rm() - thank you for the detail, I know you took longer than you had planned but I do appreciate it, For those with a similar problems in the future please see the responses below: Jenny Barnes wrote: Having tried again your suggestion of load() worked (well - it finished, which I assume it meant it worked). However not I am confused as to how I can check it has worked. I typed data.out$data which called up the data from the file - but I'm not sure if this is data from the file I have just restored as in my previously saved workspace restored Remove it from your current workspace: rm(data.out) then do the load('whatever') again: load(/some/path/to/data.out.RData) then see if its magically re-appeared in your workspace: data.out$data But now if you quit and save your workspace it'll be in your workspace again when you start up. So you could consider 'attach' instead of 'load'... Remove data.out from your current workspace, save your current workspace (with 'save()' - just like that with nothing in the parentheses), then instead of load('/some/path/to/data.out.RData') use: attach('/some/path/to/data.out.RData') This makes R search for an object called 'data.out' in that file whenever you type 'data.out'. It will find it as long as there's not a thing called 'data.out' in your workspace. So if you do attach(...) and then do: str(data.out) you'll see info about your data.out object, but then do: data.out=99 str(data.out) you'll see info about '99'. Your data.out is still happily sitting in its .RData file, its just masked by the data.out we created and set to 99. Delete that, and your data.out comes back: rm(data.out) str(data.out) # - your data object again The advantage of this is that data.out wont be stored in your current workspace again. The disadvantage is that you have to do 'attach(...whatever...)' when you start R, and that data.out can be masked if you create something with that name in your workspace. It is a handy thing to do if you create large data objects that aren't going to change much. Also, is it normal that if I type data.out.RData it says Error: object data.out.RData not found Yes, because thats the name of the _file_ on your computer and not the R object. This should be in the R manuals and help files... and I've gone on much longer than I intended to in this email :) Barry Jennifer Barnes PhD student - long range drought prediction Climate Extremes Department of Space and Climate Physics University College London Holmbury St Mary, Dorking Surrey RH5 6NT 01483 204149 07916 139187 Web: http://climate.mssl.ucl.ac.uk __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Single precision data behaviour with readBin()
Hi, what you are observing is the fact that there is always a limit in the precision a floating-point values can be stored. The value you are trying to read is stored in 4 bytes (floats). For higher precision, the value could be stored in 8 bytes (doubles). BTW, R works with 8 byte floating-toint values. Example illustrating this (R --vanilla): # Write data x - 0.05 writeBin(x, con=float.bin, size=4) writeBin(x, con=double.bin, size=8) # Read data yF - readBin(float.bin, what=double, size=4) yD - readBin(double.bin, what=double, size=8) # Display data with different precisions options(digits=7) # Default in R (unless you change it) getOption(digits) [1] 7 yF [1] 0.05 yD [1] 0.05 options(digits=8) yF [1] 0.05001 yD [1] 0.05 options(digits=12) yF [1] 0.050007451 yD [1] 0.05 # Difference between 0.5 stored as double and float log10(abs(yD-yF)) [1] -9.12780988455 # Eventually you will see the same for doubles too: options(digits=22) 1e-24 [1] 9.99924e-25 Hope this helps! Henrik On 11/10/06, Eric Thompson [EMAIL PROTECTED] wrote: Hi all, I am running R version 2.4.0 (2006-10-03) on an i686 pc with Mandrake 10.2 Linux. I was given a binary data file containing single precision numbers that I would like to read into R. In a previous posting, someone suggested reading in such data as double(), which is what I've tried: zz - file(file, rb) h1 - readBin(con = zz, what = double(), n = 1, size = 4) h1 [1] 0.050007451 Except that I know that the first value should be exactly 0.05. To get rid of the unwanted (or really unknown) values, I try using signif(), which gives me: h1 - signif(h1, digits = 8) h1 [1] 0.05001 I suppose I could use: h1 - signif(h1, digits = 7) h1 [1] 0.05 But this does not seem ideal to me. Apparently I don't understand machine precision very well, because I don't understand where the extra values are coming from. So I also don't know if this use of signif() will be reliable for all possible values. What about a value of 1.2e-8? Will this be read in as: signif(1.2034e-8, digits = 7) [1] 1.2e-08 or could this occur?: signif(1.234e-8, digits = 7) [1] 1.23e-08 Thanks for any advice. Eric Thompson Graduate Student Tufts University Civil Environmental Engineering Medford, MA 02144 __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Object attributes in R
On 10/11/06, Gabor Grothendieck [EMAIL PROTECTED] wrote: You can define your own class then define [ to act any way you would like: [.myobj - function(x, ...) { y - unclass(x)[...] Careful, this is not the same as y - NextMethod([, x, ...) /Henrik attributes(y) - attributes(x) y } tm - structure(1:10, units = sec, class = myobj) tm tm[3:4] # still has attributes On 10/11/06, Michael Toews [EMAIL PROTECTED] wrote: Hi, I have questions about object attributes, and how they are handled when subsetted. My examples will use: tm - (1:10)/10 ds - (1:10)^2 attr(tm,units) - sec attr(ds,units) - cm dat - data.frame(tm=tm,ds=ds) attr(dat,id) - test1 When a primitive class object (numeric, character, etc.) is subsetted, the attributes are often stripped away, but the rules change for more complex classes, such as a data.frame, where they 'stick' for the data.frame, but attributes from the members are lost: tm[3:5]# lost ds[-3] # lost str(dat[1:3,]) # only kept for data.frame Is there any way of keeping the attributes when subsetted from primitive classes, like a fictional attr.drop option within the [ braces? The best alternative I have found is to make a new object, and copy the attributes: tm2 - tm[3:5] attributes(tm2) - attributes(tm) However, for the data.frame, how can I copy the attributes over (without using a for loop -- I've tried a few things using sapply but no success)? Also I don't see how this is consistent with an empty index, [], where attributes are always retained (as documented): tm[] I have other concerns about the evaluation of objects with attributes (e.g. ds/tm), where the attributes from the first object are retained for the output, but this evaluation of logic is a whole other can of worms I'd rather keep closed for now. +mt __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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@stat.math.ethz.ch 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] testing for error
tryCatch() is doing exactly what you need. I consider tryCatch() an updated and more flexible version of try() making the latter history. /H On 10/9/06, Gabor Grothendieck [EMAIL PROTECTED] wrote: See: http://www.mail-archive.com/r-help@stat.math.ethz.ch/msg09925.html On 10/9/06, Jonathan Williams [EMAIL PROTECTED] wrote: Dear R Helpers, I want to test if a procedure within a loop has produced an error or not. If the procedure has produced an error, then I want to ignore its result. If it has not produced an error, then I want to use the result. The problem In order to run the loop without crashing if the procedure produces an error, I place the routine inside a try() statement. So, suppose I am trying to find the predicted values for a regression in a loop If the procedure now produces an error, I can detect it with:- if grep('Error', result)1 #and so choose not use the result but if the procedure does not produce an error, then if grep('Error', result)1 now produces the result logical(0) and the loop then fails with the message set.seed(1) cumulator=rep(0,100) for (i in 1:100){ y1=rnorm(100) x0=rbinom(100,1,0.02) x1=rbinom(100,1,0.5) x2=rbinom(100,1,0.5) x1[x0]=NA dat=data.frame(y1,x1) result=try(lm(y1~x1, na.action=na.fail, data=dat),T); print(result) x1=x2; dat2=data.frame(x1) if (grep('Error',result)1) cumulator=cumulator+predict(result,x2) } The above runs and rejects the 'result' until i=6, when lm runs and grep('Error', result) gives:- Error in if (grep(Error, pred1) 1) for (i in labels(pred1)) votes[rownames(votes) == : argument is of length zero but, predict(result,dat2) runs fine. So, how do I trap or use the 'logical(0)' state of grep('Error', result) to obtain and accumulate my result? Thanks in advance for your help Jonathan Williams __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Space required by object?
See ll() in the R.oo package. /Henrik On 9/27/06, Ben Fairbank [EMAIL PROTECTED] wrote: Does R provide a function analogous to LS() or str() that reports the storage space, on disk or in memory, required by objects? Ben Fairbank __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] printing a variable name in a for loop
Example: lst - list(variable1, variable2, variable3) for (kk in seq(along=lst)) { name - names(lst)[kk]; value - lst[[kk]]; cat(Hello,, name, value, , World,) } /Henrik On 9/26/06, Jim Lemon [EMAIL PROTECTED] wrote: Suzi Fei wrote: Hello, How do you print a variable name in a for loop? I'm trying to construct a csv file that looks like this: Hello, variable1, value_of_variable1, World, Hello, variable2, value_of_variable2, World, Hello, variable3, value_of_variable3, World, Using this: for (variable in list(variable1, variable2, variable3)){ cat(Hello,, ???variable???, variable, , World,) } This works fine if I'm trying to print the VALUE of variable, but I want to print the NAME of variable as well. This is a teetering heap of assumptions, but is this what you wanted? Suzi-1 HiYa-function(x) { cat(Hello,deparse(substitute(x)),x,World\n,sep=, ) } HiYa(Suzi) Jim __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Creating Movies with R
On 9/22/06, Gabor Grothendieck [EMAIL PROTECTED] wrote: See the flag= argument on formatC: n - 10 formatC(1:n, dig = nchar(n)-1, flag = 0) # Here is another way: n - 10 sprintf(paste(%0, nchar(n), .0f, sep = ), 1:n) sprintf(%0*.0f, nchar(n), 1:n) or even sprintf(%0*d, nchar(n), 1:n) /H On 9/22/06, J.R. Lockwood [EMAIL PROTECTED] wrote: An alternative that I've used a few times is the jpg() function to create the sequence of images, and then converting these to an mpeg movie using mencoder distributed with mplayer. This works on both windows and linux. I have a pretty self-contained example file written up that I can send to anyone who is interested. Oddly, the most challenging part was creating a sequence of file names that would be correctly ordered - for this I use: lex - function(N){ ## produce vector of N lexicograpically ordered strings ndig - nchar(N) substr(formatC((1:N)/10^ndig,digits=ndig,format=f),3,1000) } On Fri, 22 Sep 2006, Jeffrey Horner wrote: Date: Fri, 22 Sep 2006 13:46:52 -0500 From: Jeffrey Horner [EMAIL PROTECTED] To: Lorenzo Isella [EMAIL PROTECTED], r-help@stat.math.ethz.ch Subject: Re: [R] Creating Movies with R If you run R on Linux, then you can run the ImageMagick command called convert. I place this in an R function to use a sequence of PNG plots as movie frames: make.mov.plotcol3d - function(){ unlink(plotcol3d.mpg) system(convert -delay 10 plotcol3d*.png plotcol3d.mpg) } Examples can be seen here: http://biostat.mc.vanderbilt.edu/JrhRgbColorSpace Look for the 'Download Movie' links. Cheers, Jeff Lorenzo Isella wrote: Dear All, I'd like to know if it is possible to create animations with R. To be specific, I attach a code I am using for my research to plot some analytical results in 3D using the lattice package. It is not necessary to go through the code. Simply, it plots some 3D density profiles at two different times selected by the user. I wonder if it is possible to use the data generated for different times to create something like an .avi file. Here is the script: rm(list=ls()) library(lattice) # I start defining the analytical functions needed to get the density as a function of time expect_position - function(t,lam1,lam2,pos_ini,vel_ini) {1/(lam1-lam2)*(lam1*exp(lam2*t)-lam2*exp(lam1*t))*pos_ini+ 1/(lam1-lam2)*(exp(lam1*t)-exp(lam2*t))*vel_ini } sigma_pos-function(t,q,lam1,lam2) { q/(lam1-lam2)^2*( (exp(2*lam1*t)-1)/(2*lam1)-2/(lam1+lam2)*(exp(lam1*t+lam2*t)-1) + (exp(2*lam2*t)-1)/(2*lam2) ) } rho_x-function(x,expect_position,sigma_pos) { 1/sqrt(2*pi*sigma_pos)*exp(-1/2*(x-expect_position)^2/sigma_pos) } Now the physical parameters tau-0.1 beta-1/tau St-tau ### since I am in dimensionless units and tau is already in units of 1/|alpha| D=2e-2 q-2*beta^2*D ### Now the grid in space and time time-5 # time extent tsteps-501 # time steps newtime-seq(0,time,len=tsteps) Now the things specific for the dynamics along x lam1- -beta/2*(1+sqrt(1+4*St)) lam2- -beta/2*(1-sqrt(1+4*St)) xmin- -0.5 xmax-0.5 x0-0.1 vx0-x0 nx-101 ## grid intervals along x newx-seq(xmin,xmax,len=nx) # grid along x # M1 - do.call(g, c(list(x = newx), mypar)) mypar-c(q,lam1,lam2) sig_xx-do.call(sigma_pos,c(list(t=newtime),mypar)) mypar-c(lam1,lam2,x0,vx0) exp_x-do.call(expect_position,c(list(t=newtime),mypar)) #rho_x-function(x,expect_position,sigma_pos) #NB: at t=0, the density blows up, since I have a delta as the initial state! # At any t0, instead, the result is finite. #for this reason I now redefine time by getting rid of the istant t=0 to work out # the density rho_x_t-matrix(ncol=nx,nrow=tsteps-1) for (i in 2:tsteps) {mypar-c(exp_x[i],sig_xx[i]) myrho_x-do.call(rho_x,c(list(x=newx),mypar)) rho_x_t[ i-1, ]-myrho_x } ### Now I also define a scaled density rho_x_t_scaled-matrix(ncol=nx,nrow=tsteps-1) for (i in 2:tsteps) {mypar-c(exp_x[i],sig_xx[i]) myrho_x-do.call(rho_x,c(list(x=newx),mypar)) rho_x_t_scaled[ i-1, ]-myrho_x/max(myrho_x) } ###Now I deal with the dynamics along y lam1- -beta/2*(1+sqrt(1-4*St)) lam2- -beta/2*(1-sqrt(1-4*St)) ymin- 0 ymax- 1 y0-ymax vy0- -y0 mypar-c(q,lam1,lam2) sig_yy-do.call(sigma_pos,c(list(t=newtime),mypar)) mypar-c(lam1,lam2,y0,vy0) exp_y-do.call(expect_position,c(list(t=newtime),mypar)) # now I introduce the function giving the density along y: this has to include the BC of zero # density at wall rho_y-function(y,expect_position,sigma_pos) {
Re: [R] Adding .R to source file keeps R from reading it?
Hmm... sounds like you're on Windows and have the Explorer setup such that it is hiding file extensions. You can try to use list.files() from R to see if the files actually have file extension. If this is your problem, open My Computer - Tools - Folder Options... and select tab View. Make sure that Hide extensions for known file types is *NOT* selected. /H On 9/21/06, John Tillinghast [EMAIL PROTECTED] wrote: Hi, I'm updating the LMGene package from Bioconductor. Writing R Extensions suggests that all source files (the ones in the R directory) have a .R ending, so I added it to the (one) source file. The next time I installed and ran R, R didn't understand any of the functions. I tried various things and eventually went back to the file and dropped the .R ending, installed, ran R. It worked! For purposes of distributing the package, do I want to leave the name without the .R, or add the .R and change something else? [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] new version of The R Guide available on CRAN
Hi, thanks for this. I'll keep it in mind next time in teaching/referring someone to R. BTW, before the R-core guys get you ;) Just replace all places where you use library to refer to a package (see all comments on the definition of these on r-help/r-devel), e.g. Page 17: FYI, .GlobalEnv is your workspace and the package quantities are libraries that contain (among other things) the functions and datasets that we are learning about in this manual. Cheers Henrik On 8/22/06, Owen, Jason [EMAIL PROTECTED] wrote: Hello, Version 2.2 of The R Guide is available for download in the Contributed Documents section on CRAN. The R Guide is written for the beginning R user. I use the guide in my undergraduate probability and math stat sequence, but anyone with a basic understanding of statistics (who wants to learn R) should find it useful. This updated version includes sections on multiple comparisons, optimization, along with some improvements suggested by fellow R users from around the world. The entire document is under 60 pages in length. Jason -- Assistant Professor of Statistics Mathematics and Computer Science Department University of Richmond, Virginia 23173 (804) 289-8081 fax:(804) 287-6664 http://www.mathcs.richmond.edu/~wowen This is R. There is no if. Only how. Simon (Yoda) Blomberg __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] how to skip certain rows when reading data
Have a look at readTable() in the R.utils package. It can do quite a few thinks like reading subsets of rows, specify colClasses by column names etc. Implementation was done so that memory usage is as small as possible. Note the note on the help page: WARNING: This method is very much in an alpha stage. Expect it to change.. It should work though. Examples: # Read every forth row df - readTable(pathname, rows=seq(from=1, to=1000, by=4)); # Read only columns 'chromosome' and 'position'. df - readTable(pathname, colClasses=c(chromosome=character, position=double), defColClass=NULL, header=TRUE, sep=\t); # Read 'log2' data chromosome by chromosome chromosome - readTableIndex(pathname, indexColumn=3, header=TRUE, sep=\t) for (cc in unique(chromosome)) { rows - which(chromosome == cc); df - readTable(pathname, rows=rows, colClasses=c(log2=double), defColClass=NULL, header=TRUE, sep=\t); ... } Cheers Henrik On 7/27/06, Prof Brian Ripley [EMAIL PROTECTED] wrote: On Thu, 27 Jul 2006, [EMAIL PROTECTED] wrote: Dear all, I am reading the data using read.table. However, there are a few rows I want to skip. How can I do that in an easy way? Suppose I know the row number that I want to skip. Thanks so much! The easy way is to read the whole data frame and using indexing (see `An Introduction to R') to remove the rows you do not want to retain. E.g. to remove rows 17 and 137 mydf - read.table(...)[-c(17, 137), ] -- Brian D. Ripley, [EMAIL PROTECTED] Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UKFax: +44 1865 272595 __ R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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] Generating valid R code using R
Hi, I'm trying to generate valid R code using R. Parts of the task is to read a sequence of characters from file and escape them such that they can be put in quotation marks to form a valid R code string. Example: Let the input file be (four rows containing ASCII 0-255 characters): abcdeftabghijk\nlmno second row\t\a\\ fourth and so on... EOF Now, find escapeString() such that the following piece of code generates a second file called 'file2.txt' which is identical to 'file1.txt': inStr - readChar(file1.txt, nchars=999) esStr - escapeString(inStr) rCode - sprintf('cat(file=file2.txt, %s)', esStr) cat(file=foo.R, rCode) source(foo.R) For instance, quotation marks has to be escaped in order for 'rCode' to be valid, same with newlines etc. What's the best way to do this? Currently I use an ad hoc sequence of gsub() substitutions to do this, but is there a better way to create the 'rCode' string? Thanks Henrik __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] R.oo question
On 5/26/06, Omar Lakkis [EMAIL PROTECTED] wrote: This is a simple R.oo question but I, thankfully, hope that someone would explain it to me so I would better understand this work frame. I create this class: setConstructorS3(MyExample, function(param=0) { print(paste(called with param=, param)) extend(Object(), MyExample, .param = param ); }) From what is printed out, who made the second call to the class with the default param? MyExample(1) [1] called with param= 1 [1] called with param= 0# - this is line in question [1] MyExample: 0x02831708 That is because of a new US government rule requiring that one instance of every R.oo class is forwarded to the NSA. Seriously, you will see that this happens once and only once for each class defined this way and it normally happens when you create your first instance (otherwise before that). The first call to the constructor creates a so called static instance of the class. The static instance is for instance used when you type 'MyExample' to get the API coupled to class MyExample. Another example: Object Object public $(name) public $-(name, value) public [[(name) ... public objectSize(...) public print(...) public save(file=NULL, path=NULL, compress=TRUE, ...) } Technical details: The static instance is not always needed, but quite often. If needed, it has to be create at some stage and I found that having extend() to do this is quite convenient. The alternative would be to let you do it explicitly, e.g. getStaticInstance(Object). Note that there is no central registry/database keeping track of the classes defined by R.oo/Object, but all is just plain S3 classes making use of the S3/UseMethod dispatching mechanisms - that's all. There is a low-level way to figure out if the call to the constructor is for the static instance or not, but normally it is easier not to output anything in the constructor. If you want to know the low-level way, I'll have have to get back to, because I don't know it off the top of my head. I might provide a method for this if there is a need for it, e.g. hasStaticInstance(MyExample). Cheers Henrik (the author) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Avoiding a memory copy by [[
On 5/23/06, Matthew Dowle [EMAIL PROTECTED] wrote: Hi, n = 1000 L = list(a=integer(n), b=integer(n)) L[[2]][1:10] gives me the first 10 items of the 2nd vector in the list L. It works fine. However it appears to copy the entire L[[2]] vector in memory first, before subsetting it. It seems reasonable that [[ can't know that all that is to be done is to do [1:10] on the result and therefore a copy in memory of the entire vector L[[2]] is not required. Only a new vector length 10 need be created. I see why [[ needs to make a copy in general. L[[c(2,1)]] gives me the 1st item of the 2nd vector in the list L. It works fine, and does not appear to copy L[[2]] in memory first. Its much faster as n grows large. But I need more than 1 element of the vector L[[c(2,1:10)]] fails with Error: recursive indexing failed at level 2 Is there a way I can obtain the first 10 items of L[[2]] without a memory copy of L[[2]] ? I think environments will help you out here: n 1000 env - new.env() env$a - integer(n) env$b - integer(n) env$a[1:10] /Henrik Thanks! Matthew R 2.1.1 [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Avoiding a memory copy by [[
On 5/23/06, Matthew Dowle [EMAIL PROTECTED] wrote: Thanks. I looked some more and found that L$b[1:10] doesn't seem to copy L$b. If that's correct why does L[[2]][1:10] copy L[[2]] ? I forgot, this is probably what I was told in discussion about UseMethod($) the other day: The $ operator is very special. Its second argument (the one after the operator) is not evaluated. For [[ it is. This is probably also why the solution with environment works. I think some with the more knowledge about the R core has to give you the details on this, and especially why $ is special in the first place (maybe because of the example you're giving). /Henrik -Original Message- From: Prof Brian Ripley [mailto:[EMAIL PROTECTED] Sent: 23 May 2006 16:23 To: Matthew Dowle Cc: 'r-help@stat.math.ethz.ch' Subject: Re: [R] Avoiding a memory copy by [[ On Tue, 23 May 2006, Matthew Dowle wrote: Hi, n = 1000 L = list(a=integer(n), b=integer(n)) L[[2]][1:10] gives me the first 10 items of the 2nd vector in the list L. It works fine. However it appears to copy the entire L[[2]] vector in memory first, before subsetting it. It seems reasonable that [[ can't know that all that is to be done is to do [1:10] on the result and therefore a copy in memory of the entire vector L[[2]] is not required. Only a new vector length 10 need be created. I see why [[ needs to make a copy in general. L[[c(2,1)]] gives me the 1st item of the 2nd vector in the list L. It works fine, and does not appear to copy L[[2]] in memory first. Its much faster as n grows large. But I need more than 1 element of the vector L[[c(2,1:10)]] fails with Error: recursive indexing failed at level 2 Note that [[ ]] is documented to only ever return one element, so this is invalid. Is there a way I can obtain the first 10 items of L[[2]] without a memory copy of L[[2]] ? Use .Call -- Brian D. Ripley, [EMAIL PROTECTED] Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UKFax: +44 1865 272595 __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] multiple plots with par mfg
saveSubplot - function() { if (!exists(subplotPars, mode=list)) subplotPars - list(); p - par(no.readonly=TRUE); mfg - p$mfg; key - mfg[1]*(mfg[3]-1)+mfg[2]; subplotPars[[key]] - p; invisible(key); } restoreSubplot - function(mfg) { opar - par(); if (length(mfg) == 2) mfg - c(mfg, par(mfg)[3:4]); key - mfg[1]*(mfg[3]-1)+mfg[2]; p - subplotPars[[key]]; # Move 'mfg' last mfg - p$mfg; p$mfg - NULL; p$mfg - mfg; par(p); invisible(opar); } par(mfrow=c(2,2)); par(lwd=2, pch=19); plot(rnorm(10), rnorm(10)); saveSubplot(); par(lwd=1, pch=0); hist(rgamma(1000,3)); saveSubplot(); restoreSubplot(c(1,1)); points(0,0, col=red); /Henrik On 5/23/06, Romain Francois [EMAIL PROTECTED] wrote: Hi, An other possibility might be to use two devices and use dev.set to go from one to another : x11() # the first device (may be windows() or quartz() depending on you OS) plot(1,1, col=blue) # blue plot x11() # the second plot(1.2,1.2, col=red) # red plot points(1.1,1.1) # appears to bottom left of red point dev.set(dev.prev()) # switch plots points(1.1,1.1) Le 23.05.2006 17:54, Yan Wong a écrit : On 23 May 2006, at 15:57, Greg Snow wrote: The best thing to do is to create the first plot, add everything to the first plot that you need to, then go on to the 2nd plot, etc. Yes, I realise that. The problem is that the data are being simulated on the fly, and I wish to display multiple plots which are updated as the simulation progresses. So I do need to return to each plot on every generation of the simulation. If you really need to go back to the first plot to add things after plotting the 2nd plot then here are a couple of ideas: Look at the examples for the cnvrt.coords function in the TeachingDemos package (my quick test showed they work with layout as well as par(mfrow=...)). The other option is when you use par(mfg) to go back to a previous plot you also need to reset the usr coordinates, for example: Aha. I didn't realise that the usr coordinates could be stored and reset using par. Hope this helps, I think that's exactly what I need. Thank you very much. Yan __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- visit the R Graph Gallery : http://addictedtor.free.fr/graphiques mixmod 1.7 is released : http://www-math.univ-fcomte.fr/mixmod/index.php +---+ | Romain FRANCOIS - http://francoisromain.free.fr | | Doctorant INRIA Futurs / EDF | +---+ __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] R.matlab anyone ?
Hi Alex, author here - thanks for this. Indeed, there is a typo in MatlabServer.m that gives the error iff the port number is out of range. So if you set MATLABSERVER_PORT in range it should work. However, the Matlab code contains a syntax error in that statement which shouldn't be there. FYI, it should read (single quote twice): error('Cannot not open connection. Port (''MATLABSERVER_PORT'') is out of range [1023,49151]: %d', port); I've updated the package accordingly. You can install the updated version by: source(http://www.braju.com/R/hbLite.R;) hbLite(R.matlab) Best, Henrik On 5/8/06, Alexander Nervedi [EMAIL PROTECTED] wrote: Hi I have some code up and runnning in Matlab and need it for some stuff better handled in R. So R.matlab sounded terrific. However, I am having trouble getting it to go. I am using R v 2.2.1 (i know i know i need to upgrade), and Windows XP and Matlab 6.0.0.88 (R12). here is what I get. # in R GUI library(R.matlab) Loading required package: R.oo R.oo v1.1.6 (2006-04-03) successfully loaded. See ?R.oo for help. R.matlab v1.1.1 (2006-01-21) successfully loaded. See ?R.matlab for help. Matlab$startServer() Loading required package: R.utils R.utils v0.7.7 (2006-03-30) successfully loaded. See ?R.utils for help. [1] 0 # However, Matlab does open up on seperate window, but with an error message. This reads, To get started, type one of these: helpwin, helpdesk, or demo. For product information, visit www.mathworks.com. ??? Error: File: C:\R\R-2.2.1\MatlabServer.m Line: 109 Column: 45 ) expected, identifier found. So I went to MatlabServer.m and found that 108 if (port 1023 | port 49151) 109 error('Cannot not open connection. Port ('MATLABSERVER_PORT') is out of range [1023,49151]: %d', port); 110 end (the numbers are the line numbers). my guess is that I haven't been able to connect and the 0 i see from within R is a sign of this. Can anyone advice me as to what is going on. I feel there is something missing - i can get the matlab command window to come up but the connection i guess is not there. Any ideas would be really helpful. Alex. __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] load file RData which store in zip file
Hi. R can do all of this for you. See ?save.image and especially the 'compress' argument. /Henrik On 3/29/06, Muhammad Subianto [EMAIL PROTECTED] wrote: Dear R users, My situation: (1) I have limited workspace for my work harddisk (about 10 GiB). (2) I have a lot of data files in R workspace (*.RData) which most of them 200 MiB. For some reason I zip some of them, for instance filename.RData (250 MiB) to filename.zip (3MiB). In this work I have a lot of more space of my harddisk. Normally, If I want to use filename.RData for my experiment, I can do it with load(filename.RData). Then I tried to open/load load(filename.zip) Error: bad restore file magic number (file may be corrupted) -- no data loaded My question: How can I open/load filename.zip? Is there any function to open R workspace which it store in zip file? I hope some one can give me advices. Best, Muhammad Subianto version _ platform i386-pc-mingw32 arch i386 os mingw32 system i386, mingw32 status major2 minor2.1 year 2005 month12 day 20 svn rev 36812 language R __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+2h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] load huge image
On 3/27/06, Martin Maechler [EMAIL PROTECTED] wrote: Gottfried == Gottfried Gruber [EMAIL PROTECTED] on Sun, 26 Mar 2006 10:27:35 +0200 writes: Gottfried hello, i have run around 65000 regressions and Gottfried stored them in a list. then i stored the session Gottfried with save.image on my hard disk. the file is Gottfried almost 1GB. when i now want to load the image it Gottfried took tons of time. even after 12h of loading it Gottfried was not done, although the saving was done fairly Gottfried fast. I'm sure it takes so lang because you (i.e. R) run out of RAM and the machine starts to swap. Try to get access to a Linux (or other Unix-alike) machine with a 64-bit version of R and about 8 GB of RAM (maybe 4 GB is already sufficient). I guess then you should be able to read it much more quickly. For 65000 regressions, do you need more than the estimated coefficients or -- a bit more informatively -- the coef(summary( lm-fit )) result ? If you had only saved these coefficient matrices, I'm sure you'd have need **much** less memory. Gottfried i fear i have to run the regressions again and Gottfried store them in a database ... or really store what you need instead of everything ... Gottfried can i load this file? any suggestions? Do you need to have all of them in memory at once? Instead of using save.image() can't you use save()/load() on each of the regression fits? You can name the files using sprintf(regression%05d.Rdata, idx) or similar. Also, as Martin says, fit objects contains a lot of information that you might not need; remove these before saving by setting the elements you don't want to NULL. /Henrik Gottfried thanks bets regards, gg -- Gottfried --- Gottfried Gottfried Gruber Gottfried mailto:[EMAIL PROTECTED] www: Gottfried http://gogo.sehrsupa.net Gottfried __ Gottfried R-help@stat.math.ethz.ch mailing list Gottfried https://stat.ethz.ch/mailman/listinfo/r-help Gottfried PLEASE do read the posting guide! Gottfried http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+2h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] The R fork
On 3/18/06, Uwe Ligges [EMAIL PROTECTED] wrote: pau carre wrote: Hello, I would like to call a function that can take infinite time to be executed in some circumstances (which can not be easily detected). So, I would like that once the function is being executed for more than two seconds it is stopped. I have found documentation for timers but i did not found how to kill a function. Moreover, I would like not to change the function code (it should work in all R versions and I want to use the default function because of the updates in its package). On the one hand I do not think this is possible on all supported platforms, on the other hand I think non-terminating algotithms can be improved by checking number of iterations or recursion depth for some forces termination. You might want to ask the package maintainer to include such an improvement (of not bugfix) in his code. The package maintainer certainly will be happy to see your contribution. In addition, you could ask to have hooks added, see ?seeHook. Then you could write a hook function that generates an error, e.g. stop(), which you then can catch with tryCatch(). If you define your own error class, say, TimeoutError, your calling code will look like tryCatch(neverEndingFunction(), TimeoutError=function(ex) print(ex)) Alternatively, you could send a SIGINT (corresponds to Ctrl-C) signal to R from outside R. On Unix you can do something like: pkill -INT -U $user R from a shell. I do not know how to send a SIGINT on Windows (the Windows application 'termkill' will just kill R if you try that). In R you catch this interrupt signal via tryCatch(neverEndingFunction(), interrupt=function(intr) print(intr)) Then interrupt will exit neverEndingFunction() and continue with the next line of code. If you can schedule or write a shell script that sends the SIGINT signal every two minutes this would work for you. It is possible that you may be able to do all of this from within R; write Tcl(Tk) code, which R supports, that calls 'pkill' at certain times. I think this is possible even though R is single threaded, but I'm not a Tcl hacker so you have to ask someone else about this. Interrestingly, the last few days I've tried to find a way for a function to send an interrupt itself. See r-help thead New simpleExit condition (Mar 14-Mar 16) for details. Solving that would be one step closer to solve your problem. (No, system(pkill -INT ...) does not seem to work). Cheers Henrik Uwe Ligges Pau __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] storing via for (k in 1:100) {}
See ?sprintf and/or ?paste. /Henrik On 3/18/06, Stefan Semmeling [EMAIL PROTECTED] wrote: daer list, i want to save a result as mentioned above. for (i in 1:100) { a[i] - write.table(a[i], C:/.../resulti) } how is the correct way to save the results? thank you stefan __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+1h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] How to divide too long labels?
On 3/18/06, Atte Tenkanen [EMAIL PROTECTED] wrote: Is there any possibility to divide too long text in a plot to two or more lines, when using labels-parameter in the text()-command? Here is an example picture: http://users.utu.fi/attenka/253.jpeg My example script is something like this: text(1,0.7,labels=Chordnames[fnid(pcs%%12)]) # according to Larry Solomon's table http://solomonsmusic.net/pcsets.htm Chordnames is a long vector with long character strings. plot(1, xlab=First row\nSecond row) text(1,1, labels=First row\nSecond row) To insert a '\n' at sensible positions such as between two words, look at regexpr() and substring() and paste(). If you labels have a known pattern you might be able to use gsub(). /Henrik Atte Tenkanen University of Turku Finland __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+1h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Traffic on R-Help Mailing List
Hi, there's been plenty of messages sent during that period. The r-help archive is at https://www.stat.math.ethz.ch/pipermail/r-help/ (you can find this via http://www.r-project.org/ - Mailing Lists - r-help/web interface - R-help Archives). There are similar pages for r-devel and the other lists. There you should be able to see what messages have been sent. Cheers Henrik On 3/17/06, Knut Krueger [EMAIL PROTECTED] wrote: I am amazed that the traffic decreased the last days. I am afraid that there is any problem with the spamfilter of my provider. There are not messages from march 04rd until march 15th, Two messages from march 16 and nothing else since march 03rd Please answer also with PM to the mail address. I hope I will solve the problem. Thank you Knut __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] handling warning messages
On 3/16/06, Martin Morgan [EMAIL PROTECTED] wrote: also tryCatch tryCatch( warning(a warning), + warning = function(w) { +paste(Caught:, conditionMessage( w )) + }) [1] Caught: a warning BE CAREFUL! When a condition, such as warnings and errors, are caught by tryCatch() the expression that follows are NOT evaluated! This is probably not what you want/expected. tryCatch({ print(1) warning(a warning) print(We never get here!) }, warning=function(w) { paste(Caught:, conditionMessage(w)) }) [1] 1 [1] Caught: a warning /Henrik ronggui [EMAIL PROTECTED] writes: see ?options 'warn': sets the handling of warning messages. If 'warn' is negative all warnings are ignored. If 'warn' is zero (the default) warnings are stored until the top-level function returns. If fewer than 10 warnings were signalled they will be printed otherwise a message saying how many (max 50) were signalled. A top-level variable called 'last.warning' is created and can be viewed through the function 'warnings'. If 'warn' is one, warnings are printed as they occur. If 'warn' is two or larger all warnings are turned into errors. 'warning.expression': an R code expression to be called if a warning is generated, replacing the standard message. If non-null it is called irrespective of the value of option 'warn'. 'warnings.length': sets the truncation limit for error and warning messages. A non-negative integer, with allowed values 100...8192, default 1000. 2006/3/16, Sigal Blay [EMAIL PROTECTED]: Is there any way to store the value of warnings but avoid printing them? A simplified example: out - c(0.2,0.3,0.4) var - c(2,3,4) outcome - glm(out ~ var, family=binomial()) Warning message: non-integer #successes in a binomial glm! in: eval(expr, envir, enclos) I don't like the warning printed, but I would like to be able to check it's value after the top-level function has completed and than decide weather to print it or not. Thanks, Sigal Blay Statistical Genetics Working Group Department of Statistics and Actuarial Science Simon Fraser University __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- 黄荣贵 Deparment of Sociology Fudan University __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+1h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] setMethod confusion
On 3/15/06, Martin Maechler [EMAIL PROTECTED] wrote: Stephen == Stephen Henderson [EMAIL PROTECTED] on Tue, 14 Mar 2006 16:32:56 - writes: Stephen Hello I've checked through previous postings but Stephen don't see a fully equivalent problem-just a few Stephen hints. I have been trying to set a new method for Stephen the existing function table or Stephen as.data.frame.table for my class tfSites. Stephen Taking out all the useful code and just returning Stephen the input class I get the error setMethod(table, tfSites, function(.Object) .Object) Stephen Error in conformMethod(signature, mnames, fnames, Stephen f) : In method for function table: formal Stephen arguments omitted in the method definition cannot Stephen be in the signature (exclude = tfSites) setMethod(as.data.frame.table, tfSites, function(.Object) .Object ) Stephen Error in conformMethod(signature, mnames, fnames, Stephen f) : In method for function as.data.frame.table: Stephen formal arguments omitted in the method definition Stephen cannot be in the signature (x = tfSites) Stephen What does this mean? Is there something peculiar Stephen about the table function? Is it because it takes Stephen arguments beginning table(..., etc) Yes. Since table's argument list starts with ... you cannot directly write S4 methods for it. Although not fully tested, but a workaround could be to i) define an S4 method tableS4(), then ii) rename table() to table.default() and iii) make table() an S3 generic function, and finally iv) define table.tfSites() to call tableS4(). Would this work? If so, step (ii)-(iv) can be done in one step using the R.oo package. Example: library(R.oo) setClass(fSites, representation(x=numeric, y=numeric)) setGeneric(tableS4, function(.Object, ...) standardGeneric(tableS4)) setMethod(tableS4, fSites, function(.Object) .Object) setMethodS3(table, fSites, function(.Object, ...) tableS4(.Object, ...)) Test; x - new(fSites) table(x) An object of class fSites Slot x: numeric(0) Slot y: numeric(0) X - rpois(20, 1) table(X) X 0 1 2 3 10 7 2 1 But, what's wrong with S3 in the first place? ;) /Henrik One could consider changing table's argument list to become (x, ..., exclude = c(NA, NaN), dnn = list.names(...), deparse.level = 1) but that's not entirely trivial to do back compatibly, since table() produces *named* dimnames from its arguments in ... and we'd want to make sure that this continues to work as now even when the first argument is formally named 'x'. E.g., X - rpois(20, 1) table(X) X 0 1 2 3 7 10 2 1 should continue to contain X as names(dimnames(.)). Of course this has now become a topic for R-devel rather than R-help. Martin Maechler, ETH Zurich __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+1h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Additional arguments in S3 method produces a warning
It is even better/more generic(!) to have: extract - function(...) UseMethod(extract) Specifying the object argument or the method arguments of a generic function will restrict any other methods with the same name to have the same argument. By also excluding the object argument, default functions such as search() will also be called if the generic function is called without any arguments. [http://www.maths.lth.se/help/R/RCC/] /Henrik On 3/15/06, Gabor Grothendieck [EMAIL PROTECTED] wrote: Define extract like this: extract - function(e, n, ...) UseMethod(extract) # test -- no warning extract(tp, no.tp = FALSE, peak = TRUE, pit = FALSE) On 3/15/06, Philippe Grosjean [EMAIL PROTECTED] wrote: Hello, I just notice this: x - c(1:4,0:5, 4, 11) library(pastecs) Loading required package: boot tp - turnpoints(x) extract(tp, no.tp = FALSE, peak = TRUE, pit = FALSE) [1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE Warning message: arguments after the first two are ignored in: UseMethod(extract, e, n, ...) extract(tp) [1] 0 0 0 1 -1 0 0 0 0 1 -1 0 Warning message: arguments after the first two are ignored in: UseMethod(extract, e, n, ...) My extract.turnpoints() function produces warnings. I can easily spot the origin of this warning: extract function (e, n, ...) UseMethod(extract, e, n, ...) extract.turnpoints function (e, n, no.tp = 0, peak = 1, pit = -1, ...) { if (missing(n)) n - length(e) res - rep(no.tp, length.out = e$n) res[e$pos[e$peaks]] - peak res[e$pos[e$pits]] - pit if (n length(res) n 0) res - res[1:n] res } This is because my extract.turnpoints() method defines more arguments than 'e' and 'n' in the generic function. However, 1) I though that the '...' argument in S3 generic function was there to allow defining/passing additional arguments in/to S3 methods. Is this correct? If yes, why the warning? 2) Despite the warning says arguments after the first two are ignored, this appears not to be the case: in this example, 'no.tp', 'peak' and 'pit' arguments are taken into account, as you can see (different behaviour if you give other values to them). I am a little bit lost. Could someone help me, please. Best, Philippe Grosjean -- ..°})) ) ) ) ) ) ( ( ( ( (Prof. Philippe Grosjean ) ) ) ) ) ( ( ( ( (Numerical Ecology of Aquatic Systems ) ) ) ) ) Mons-Hainaut University, Pentagone (3D08) ( ( ( ( (Academie Universitaire Wallonie-Bruxelles ) ) ) ) ) 8, av du Champ de Mars, 7000 Mons, Belgium ( ( ( ( ( ) ) ) ) ) phone: + 32.65.37.34.97, fax: + 32.65.37.30.54 ( ( ( ( (email: [EMAIL PROTECTED] ) ) ) ) ) ( ( ( ( (web: http://www.umh.ac.be/~econum ) ) ) ) ) http://www.sciviews.org ( ( ( ( ( .. __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+1h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] info() function?
library(R.oo) ll() member data.class dimension object.size 1 anumeric 10004028 2author character 1 112 3 expnumeric 1 36 4 last.warning list 2 488 5object function NULL 864 6 row character 1 72 7 USArrests data.frame c(50,4)4076 8 VADeaths matrixc(5,4) 824 9 value character 1 72 with NA counts: naCount - function(x, ...) ifelse(is.vector(x), sum(is.na(x)), NA) properties - c(data.class, dimension, object.size, naCount) ll(properties=properties) member data.class dimension object.size 1 anumeric 10004028 2author character 1 112 3 expnumeric 1 36 4 last.warning list 2 488 5 naCount function NULL 864 6object function NULL 864 7properties character 4 212 8 row character 1 72 9 USArrests data.frame c(50,4)4076 10 VADeaths matrixc(5,4) 824 11value character 1 72 FYI: In next version of R.oo, there will probably be some kind of option to set the default 'properties' argument so that this must not be given explicitly by default. Cheers Henrik On 3/8/06, Robert Lundqvist [EMAIL PROTECTED] wrote: I would like to have some function for getting an overview of the variables in a worksheet. Class, dimesions, length, number of missing values,... Guess it wouldn't be that hard to set up such a function, but I guess there are others who have made it already. Or is it already a standard feature in the base package? Any suggestions? Robert __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+1h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] returning the largest element in an array/matrix?
This is a problem how to convert vector indices to array indices. Here is a general solution utilizing the fact that matrices are stored column by column in R (this extends to arrays of any dimension): arrayIndex - function(i, dim) { ndim - length(dim); # number of dimension v - cumprod(c(1,dim)); # base # Allocate return matrix j - matrix(NA, nrow=length(i), ncol=ndim); i - (i-1); # one-based indices for (kk in 1:ndim) j[,kk] - (i %% v[kk+1])/v[kk]; 1 + floor(j); # one-based indices } # Now we can the optimized which.max() function: m - matrix(1:14, nrow=7, ncol=4) arrayIndex(which.max(m), dim=dim(m)) Gives: [,1] [,2] [1,]72 # The less efficient: arrayIndex(which(m==max(m)), dim=dim(m)) Gives: [,1] [,2] [1,]72 [2,]74 BTW, isn't there such a function in R already? I tried to find it, but I couldn't. Cheers Henrik On 3/7/06, Petr Pikal [EMAIL PROTECTED] wrote: Hi If you do not insist on which.max() you can use which(mat==max(mat), arr.ind=T) HTH Petr On 6 Mar 2006 at 20:55, Michael wrote: Date sent: Mon, 6 Mar 2006 20:55:20 -0800 From: Michael [EMAIL PROTECTED] To: R-help@stat.math.ethz.ch Subject:[R] returning the largest element in an array/matrix? Hi all, I want to use which.max to identify the maximum in a 2D array/matrix and I want argmin and return the row and column indices. But which.max only works for vector... Is there any convinient way to solve this problem? Thanks a lot! [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Petr Pikal [EMAIL PROTECTED] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Making an S3 object act like a data.frame
Hi. On 3/7/06, hadley wickham [EMAIL PROTECTED] wrote: [.ggobiDataset - function(x, ..., drop=FALSE) { x - as.data.frame(x) NextMethod([, x) } [[.ggobiDataset - function(x, ..., drop=FALSE) { x - as.data.frame(x) NextMethod([[, x) } $.ggobiDataset - function(x, ..., drop=FALSE) { x - as.data.frame(x) NextMethod($, x) } class(x) [1] ggobiDataset data.frame x[1:2,1:2] total_bill tip 1 16.99 1.01 2 10.34 1.66 x[[1]] [1] 16.99 10.34 21.01 23.68 24.59 25.29 8.77 26.88 15.04 14.78 10.27 35.26 [13] 15.42 18.43 14.83 21.58 10.33 16.29 16.97 20.65 17.92 20.29 15.77 39.42 ... x$total_bill Error in $.default(x, total_bill) : invalid subscript type where/how is $.default() defined? I don't have one; getAnywhere($.default) no object named '$.default' was found /Henrik What do I need to do to get $.ggobiDataset to imitate a data.frame like [ and [[ do? Thanks, Hadley __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Adding header lines to a dataframe that is exported using write.csv
Just a tips: When you add headers to tabulate files like yours, it is convenient to start each header line with a '#' (like an R comment), because then read.table() will not complain about the header lines. It is easy to strip the '#' off the header lines, i.e. grep(^#, , hlines) before further parsing. /Henrik On 2/25/06, Mark [EMAIL PROTECTED] wrote: I would like to export a dataframe to a .csv using: write.csv(dataframe,dataframe.csv) but I need to add four header lines to the csv that are not part of the dataframe (which itself has a line of column headers). The difficulty (for me, at least!) lies in the requirement that certain elements of the header (X, Y and the number of Qs - please see example below) must be defined based on the number of rows and columns in the dataframe, which vary depending on the input file. Here's what the 3 .csv header lines should look like, followed by a number of dataframe rows (i.e., these lines are not R code, but are what R will produce). X, plots #where X=number of rows in the dataframe Y, species #where Y=number of columns in the dataframe ,Q,Q,Q,Q,Q #where the number of Qs=the number of columns in the dataframe Those 3 .csv header lines would be followed by dataframe, which consists of one row containing column headers and X data rows: ,spec1,spec2,spec3,sp3c4,spec5 #these are the dataframe's column headers plot1,15.84,0,0,792,7 #this is an example data row In case the above is unclear, I have also attached a small .csv as an example of what the output should look like. Thank you. Mark __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Henrik Bengtsson Mobile: +46 708 909208 (+1h UTC) __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] R and Power Point
On 2/14/06, Duncan Murdoch [EMAIL PROTECTED] wrote: On 2/14/2006 9:08 AM, Michael Kubovy wrote: On Feb 14, 2006, at 1:46 AM, Erin Hodgess wrote: I'm using R in a time series class. ... I have decided to put together Power Point slides for the teaching. ... I am currently saving the R screen as WMF files and inserting them into PowerPoint. While this works, it seems that there might be a simpler method. Hi Erin, For presentations I use LaTeX with beamer.cls and Sweave to access R. The results are legible and attractive. The method is not simple at first, since you must understand how to use beamer.cls and Sweave. But once you're in production mode, it's a delight. I'd be happy to share templates. Please put some up on the web somewhere! I'm just learning beamer, and don't need it for R right now, but I'm sure I will eventually. Duncan Murdoch P.S. How do I add page numbers to slides? I see in the manual a section called The Headline and Footline that apparently tells me how to do it using an option [page number], but I don't see where to put that. A ten second - I have to run - cross my fingers that I'm correct reply: one way is to use pre-defined templates. Try to add \useoutertheme{infolines} which should give you a line of author, short title, date, and *frame* number. /Henrik __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] chm.help in windows
Same in R v2.2.1 patched (2006-01-01 r36947) and Rv2.3.0 (2006-01-01 r36947). /Henrik Thomas Steiner wrote: options(chmhelp=TRUE) help(package=fCalendar) does not open teh windows help browser, but help(CalendarData, package=fCalendar) does. Why? A bug? I use R 2.1.1 under Windows2000 Thomas __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
[R] LaTeX slide show (Was: Re: Taking code from packages)
Duncan Murdoch wrote: On 1/13/2006 2:04 AM, Ales Ziberna wrote: Hello! [snip] (I'm a little sensitive about dependencies now, since the LaTeX seminar template I've used a few times no longer works. It depends on too many LaTeX packages, and someone, somewhere has introduced incompatibilities in them. Seems like I'll be forced to use Powerpoint or Impress.) Try LaTeX Beamer! It is the best thing that happend to LaTeX in a long time. Simply beautiful, intuitive and very easy to use, and it's not yet another 'seminar' or 'prosper'. Part of MikTeX now. See http://latex-beamer.sourceforge.net/ for documentation, examples etc. Cheers Henrik Duncan Murdoch [snip] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] R - Wikis and R-core
[EMAIL PROTECTED] wrote: Hello Martin and others, I am happy with this decision. I'll look a little bit at this next week. Best, Philippe Grosjean We've had a small review time within R-core on this topic, amd would like to state the following: -- The R-core team welcomes proposals to develop an R-wiki. - We would consider linking a very small number of Wikis (ideally one) from www.r-project.org and offering an address in the r-project.org domain (such as 'wiki.r-project.org'). - The core team has no support time to offer, and would be looking for a medium-term commitment from a maintainer team for the Wiki(s). - Suggestions for the R documentation would best be filtered through the Wiki maintainers, who could e.g. supply suggested patches during the alpha phase of an R release. -- Our main concerns have been about ensuring the quality of such extra documentation projects, hence the 2nd point above. Several of our more general, not mainly R, experiences have been of outdated web pages which are continued to be used as reference when their advice has long been superseded. I think it's very important to try ensuring that this won't happen with an R Wiki. [Tried to send the following a few days ago, but had a problem with my connection:] What about adding a best before date on Wiki pages and let moderators extend such dates (by a simple click). If the date for a page is not updated, there will be a warning on that page telling the reader that the content might not be fully valid. MediaWiki is a good solution because there you can write equations in LaTeX, which are generated as Math-ML(?) and/or bitmap images. This feature might be in other wiki system too, I don't know. That's my $0.02 Henrik Martin Maechler, ETH Zurich PhGr == Philippe Grosjean [EMAIL PROTECTED] on Sun, 8 Jan 2006 17:00:44 +0100 (CET) writes: PhGr Hello all, Sorry for not taking part of this PhGr discussion earlier, and for not answering Detlef PhGr Steuer, Martin Maechler, and others that asked more PhGr direct questions to me. I am away from my office and PhGr my computer until the 16th of January. PhGr Just quick and partial answers: 1) I did not know PhGr about Hamburg RWiki. But I would be happy to merge PhGr both in one or the other way, as Detlef suggests it. PhGr 2) I choose DokuWiki as the best engine after a PhGr careful comparison of various Wiki engines. It is the PhGr best one, as far as I know, for the purpose of PhGr writting software documentation and similar PhGr pages. There is an extensive and clearly presented PhGr comparison of many Wikki engines at: PhGr http://www.wikimatrix.org/. PhGr 3) I started to change DokuWiki (addition of various PhGr plugins, addition of R code syntax coloring with PhGr GESHI, etc...). So, it goes well beyond all current PhGr Wiki engines regarding its suitability to present R PhGr stuff. PhGr 4) The reasons I did this is because I think the Wiki PhGr format could be of a wider use. I plan to change a PhGr little bit the DokuWiki syntax, so that it works with PhGr plain .R code files (Wiki part is simply embedded in PhGr commented lines, and the rest is recognized and PhGr formatted as R code by the Wiki engine). That way, the PhGr same Wiki document can either rendered by the Wiki PhGr engine for a nice presentation, or sourced in R PhGr indifferently. PhGr 5) My last idea is to add a Rpad engine to the Wiki, PhGr so that one could play with R code presented in the PhGr Wiki pages and see the effects of changes directly in PhGr the Wiki. PhGr 6) Regarding the content of the Wiki, it should be PhGr nice to propose to the authors of various existing PhGr document to put them in a Wiki form. Something like PhGr Statistics with R PhGr (http://zoonek2.free.fr/UNIX/48_R/all.html) is written PhGr in a way that stimulates additions to pages in PhGr perpetual construction, if it was presented in a Wiki PhGr form. It is licensed as Creative Commons PhGr Attribution-NonCommercial-ShareAlike 2.5 license, that PhGr is, exactly the same one as DokuWiki that I choose for PhGr R Wiki. Of course, I plan to ask its author to do so PhGr before putting its hundreds of very interesting pages PhGr on the Wiki... I think it is vital to have already PhGr something in the Wiki, in order to attract enough PhGr readers, and then enough contributors! PhGr 7) Regarding spamming and vandalism, DokuWiki allows PhGr to manage rights and users, even individually for PhGr pages. I think it would be fine to lock pages that PhGr reach a certain maturity (read-only / editable by PhGr selected users only) , with link to a
Re: [R] [R-pkgs] sudoku
I replied all to the original message, but since that was to [EMAIL PROTECTED] it might not have gone out there, did it? If not, below is my reply again. [You have restrict the randomization so that you permute within and between block rows/columns.] /Henrik Original Message Subject: Re: [R] [R-pkgs] sudoku Date: Sat, 07 Jan 2006 09:36:54 +1100 From: Henrik Bengtsson [EMAIL PROTECTED] To: Brahm, David [EMAIL PROTECTED] CC: [EMAIL PROTECTED] References: [EMAIL PROTECTED] Brahm, David wrote: Any doubts about R's big-league status should be put to rest, now that we have a Sudoku Puzzle Solver. Take that, SAS! See package sudoku on CRAN. The package could really use a puzzle generator -- contributors are welcome! Last summer I put a quick generator together after discussing with some friends how these games a generate (and enumerated). I don't know if it is a correct/complete generator, but consider an empty game with 3x3 grids each with 3x3 cells. Create the initial board by adding 1:9 in the first row, the c(2:9,1), in the second and so on, to make sure you have one correct board. From this you can now generate all(?) other possible boards by permuting rows and columns. You can for instance use a random seed enumerate all such boards. Finally, you want to remove some of cells, which you also can by sampling using known random seeds. See attached code. Example: source(Sudoku.R) Sudoku$generate() [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,]1 NA34 NA NA NA8 NA [2,]4 NA NA NA8 NA NA NA NA [3,] NA8 NA1 NA3456 [4,]2 NA NA NA NA NA NA NA1 [5,] NA67 NA NA NA2 NA4 [6,]8 NA NA NA NA NA NA6 NA [7,] NA NA5 NA NA89 NA NA [8,]6 NA891 NA3 NA NA [9,] NA1 NA3 NA NA NA78 Sudoku$generate(1) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,]3 NA25 NA NA NA9 NA [2,]9 NA NA NA3 NA NA NA NA [3,] NA4 NA8 NA7231 [4,]2 NA NA NA NA NA NA NA6 [5,] NA34 NA NA NA1 NA9 [6,]8 NA NA NA NA NA NA5 NA [7,] NA NA9 NA NA26 NA NA [8,]7 NA691 NA3 NA NA [9,] NA2 NA6 NA NA NA18 Sudoku$generate(2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,]7 NA61 NA NA NA2 NA [2,]1 NA NA NA3 NA NA NA NA [3,] NA2 NA7 NA5981 [4,]8 NA NA NA NA NA NA NA5 [5,] NA91 NA NA NA7 NA8 [6,]5 NA NA NA NA NA NA9 NA [7,] NA NA5 NA NA72 NA NA [8,]9 NA832 NA5 NA NA [9,] NA1 NA6 NA NA NA79 /Henrik -- David Brahm ([EMAIL PROTECTED]) [[alternative HTML version deleted]] ___ R-packages mailing list [EMAIL PROTECTED] https://stat.ethz.ch/mailman/listinfo/r-packages __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html roger bos wrote: As far as generating a sudoku, it can't be too hard because I have a program on my cell phone that does it with a size less than 325K. I don't know the best way to generate these, but one way I was thinking of was starting with a filled up one then randomize the columns and rows. Then make some of them blank. The cell-phone version often generates puzzles that have non-unique solutions. Though I admit this is sometimes annoying, it also can make the puzzle harder. Thanks, Roger On 1/9/06, Martin Maechler [EMAIL PROTECTED] wrote: First, thanks a lot! to David Brahms for finally tackling this important problem, and keeping the R language major league ! ;-) :-) {but the thanks! is meant seriously!} Detlef == Detlef Steuer [EMAIL PROTECTED] on Sun, 8 Jan 2006 12:21:52 +0100 writes: Detlef Hey, you spoiled my course! :-) Detlef I planned using this as an excersise. Alternative Detlef ideas anyone ... Well, you could *add* to it: 1) When I have been thinking about doing this myself (occasionally in the past weeks), I had always thought that finding *ALL* solutions was a very important property of the algorithm I would want to design. (since this is slightly more general and useful than proofing uniqueness which the current algorithm does not yet do anyway). 2) The current sudoku() prints the result itself and returns a matrix; improved, it should return an object of class sudoku, with a print() and a plot
Re: [R] repeat { readline() }
Prof Brian Ripley wrote: On Sun, 8 Jan 2006, Prof Brian Ripley wrote: Ctrl-Break works: see the rw-FAQ and README.rterm. (You'll need a return to see a new prompt.) It is related to your reading directly from the console, so Ctrl-C is getting sent to the wrong place, I believe. (There's a comment from Guido somewhere in the sources about this, and this seems corroborated by the fact that Ctrl-C will interrupt under Rterm --ess.) Although the comment is there (in psignal.c), on closer examination the cause is a change Guido made to getline.c, so Ctrl-C is treated as a character during keyboard input. I doubt if that was intentional (0 is not the default state) and I have changed it for R-devel.\ Thank you very much this. Henrik On Sun, 8 Jan 2006, Henrik Bengtsson wrote: Hi. Using Rterm v2.2.1 on WinXP, is there a way to interrupt a call like repeat { readline() } without killing the Command window? Ctrl+C is not interrupting the loop: R : Copyright 2006, The R Foundation for Statistical Computing Version 2.2.1 Patched (2006-01-01 r36947) snip/snip repeat { readline() } ^C ^C ^C ^C On Unix it works. The problem seems to get the interrupt signal to occur outside the readline() call so that repeat is interrupted. Doing repeat { readline(); Sys.sleep(3) } and it is likely that can generate an interrupt signal outside readline(). It seem like readline()/readLines(n=1) or an underlying method catches the interrupt signal quietly and just waits for a symbol to come through. Try readline() by itself and press Ctrl+C. Maybe this is a property of the Windows Command terminal, I don't know, but is it a wanted feature and are R core aware of it? Note that, in Rgui it is possible to interrupting such a loop by pressing ESC. Cheers Henrik __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Brian D. Ripley, [EMAIL PROTECTED] Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UKFax: +44 1865 272595 __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
[R] repeat { readline() }
Hi. Using Rterm v2.2.1 on WinXP, is there a way to interrupt a call like repeat { readline() } without killing the Command window? Ctrl+C is not interrupting the loop: R : Copyright 2006, The R Foundation for Statistical Computing Version 2.2.1 Patched (2006-01-01 r36947) snip/snip repeat { readline() } ^C ^C ^C ^C On Unix it works. The problem seems to get the interrupt signal to occur outside the readline() call so that repeat is interrupted. Doing repeat { readline(); Sys.sleep(3) } and it is likely that can generate an interrupt signal outside readline(). It seem like readline()/readLines(n=1) or an underlying method catches the interrupt signal quietly and just waits for a symbol to come through. Try readline() by itself and press Ctrl+C. Maybe this is a property of the Windows Command terminal, I don't know, but is it a wanted feature and are R core aware of it? Note that, in Rgui it is possible to interrupting such a loop by pressing ESC. Cheers Henrik __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Using 'polygon' in a 3d plot
Ted Freeman wrote: I'm new to R, after many years of using Matlab. I've found the R function 'polygon' to be nearly equivalent to the Matlab function 'patch'. For example, the R commands: plot(c(0, 5), c(0, 4), type = 'n', asp = 1, ann = FALSE) x - c(1, 2, 2, 1.5, 1) z - c(1, 1, 2, 1.7, 2) polygon(x, z, col = 'green') produce a plot with a small green shape exactly as I expect. A nearly identical plot can be made in Matlab with these commands: x = [1, 2, 2, 1.5, 1]; z = [1, 1, 2, 1.7, 2]; patch(x, z, 'g') axis([0, 5, 0, 4]) box on In Matlab I am able to extend this quite easily to a three-dimensional plot by simply adding one more vector argument to 'patch'. I don't see how to do this in R using 'polygon'. (I've primarily looked at scatterplot3d.) Is there another function I can use? Since I expect that many of you do not use Matlab, I've put two graphics showing the example above (Plot 1) and a similar three-dimensional plot (Plot 2) on this page: http://staff.washington.edu/freeman/patch.html. Hi, I've got a plot3d() and polygon3d() function in the R.basic package (http://www.braju.com/R/). Example: library(R.basic) # plot3d() and polygon3d() xb - c(0, 4, 4, 0, 0) yb - c(0, 3, 3, 0, 0) zb - c(0, 0, 4, 4, 0) plot3d(xb,yb,zb, type=l, theta=35, phi=30) x - c(0.8, 1.6, 1.6, 1.2, 0.8) y - c(0.6, 1.2, 1.2, 0.9, 0.6) z - c(1, 1, 2, 1.7, 2) polygon3d(x,y,z, col=green) This gives a similar plot to what Matlab creates. /Henrik It's Plot 2 that I'd like to be able to reproduce in R. Thanks for any advice! -- Ted __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Age of an object?
If R would have timestamps telling when any object was last modified, we could extend R with a 'GNU make'-style functionality (or syntax) together with some fancy caching to persistent storage (files, data bases, ...). That would really nice! As B.R. and M.M. writes, timestamping is most suited for higher level data structures and not simple data types, because the over head would be too large. /Henrik Philippe Grosjean wrote: Martin Maechler wrote: Trevor == Trevor Hastie [EMAIL PROTECTED] on Tue, 13 Dec 2005 12:51:34 -0800 writes: Trevor It would be nice to have a date stamp on an object. Trevor In S/Splus this was always available, because objects were files. [are you sure about always available? In any case, objects were not single files anymore for a long time, at least for S+ on windows, and AFAIK also on unixy versions recently ] This topic has come up before. IIRC, the answer was that for many of us it doesn't make sense most of the time: I remember it was discussed several times. I don't remember why it was considered too difficult to do. If you work with *.R files ('scripts') in order to ensure reproducibility, you will rerun -- often source() -- these files, and the age of the script file is really more interesting. Also, I *always* use the equivalent of q(save = no) and almost only use save() to particularly save the results of expensive computations {often, simulations}. OK, now let me give examples where having such an information would ease the work greatly: you have a (graphical) view of the content of an object (for instance, the one using the view button in R commander), or you have a graphical object explorer that has a cache to speed up display of information about objects in a given workspace (for instance, the SciViews-R object explorer). What a wonderful feature it will be to tell if an object was changed since last query. In the view, one could have a visual clue if it is up-to-date or not. In the object explorer, I could update information only for objects that have changed... Trevor I have looked around, but I presume this information is not available. I assume you will get other answers, more useful to you, which will be based on a class of objects which carry an 'creation-time' attribute. Yes, but that would work only for objects designed that way, and only if the methods that manipulate that object do the required housework to update the 'last-changed' attribute (the question was about last access of an object, not about its creation date, so 'last-changed' is a better attribute here). If you access the object directly with, let's say, [EMAIL PROTECTED] - newvalue, that attribute is not updated, isn't it? Best, Philippe Grosjean Martin Maechler, ETH Zurich __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
[R] About help on 'mahalanobis'
Hi, help on 'mahalanobis' (in the stats package in Rv2.2.0) now says: Description: Returns the Mahalanobis distance of all rows in 'x' and the vector mu='center' with respect to Sigma='cov'. This is (for vector 'x') defined as D^2 = (x - mu)' Sigma^{-1} (x - mu) It does return D^2 as written. However, would the text be more clear if it says Returns the _squared_ Mahalanobis distance D^2... instead? If so, then text in the example code, e.g. ##- Here, D^2 = usual Euclidean distances and the title of the first plot will also have to be updated. Compare this with what dist() in the same package returns. When asking for the Equlidean distance (matrix) between rows in a matrix, we get D not D^2, e.g. dist(c(1,3)) == 2. Cheers Henrik __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Row wise function call.
Vasundhara Akkineni wrote: I have another issue.i have a function which calculates the log2(col i /col2) value, where i stands for columns 3,4,...etc. data-read.table(table.txt, header=TRUE) iratio-function(x){ for(n in 3:ncol(data)){ z-log2(data[x,n]/data[x,2]) } } Where x- the row number of the data frame(data). i want to store the ratios for each row in a object z, which can be accessed outside the function. How can i do this? Just return the result at the end of the function. Since you want to return log-ratios for many pairs, I would suggest to stick them in a new data frame, or since they results are all of the same data type, a matrix instead. Example: iratio - function(rows) { # Create (pre-allocate) empty matrix poulated with NAs z - matrix(NA, nrow=length(x), ncol=ncol(data)-3+1); for(col in 3:ncol(data)) { z[,col-3+1] - log2(data[rows,col] / data[rows,2]) } z; # or equivalent 'return(z)'; not often seen in R code. } You should try to look into introductions to R (sorry I don't know any off hand, but just search google); this is all things you need to learn. Also, you learn a lot from reading other people's code snippets. When you understand R better, you'll also realize that the above can be done in one line of code like this: z - log2(data[rows,3:ncol(data)] / data[rows,2]); Cheers Henrik PS. I haven't actually tested the above code in R; there might be typos. DS. Thanks, Vasu. [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Superimpose Histograms
See library(R.basic) example(plot.histogram) x1 - rnorm(1000, 0.4, 0.8) x2 - rnorm(1000, 0.0, 1.0) x3 - rnorm(1000, -1.0, 1.0) hist(x1, width=0.33, offset=0.00, col=blue, xlim=c(-4,4), main=Histogram of x1, x2 x3, xlab=x1 - blue, x2 - red, x3 - green) hist(x2, width=0.33, offset=0.33, col=red, add=TRUE) hist(x3, width=0.33, offset=0.66, col=green, add=TRUE) It overloads the default plot.histogram() (called when you do hist()) so it takes arguments 'offset' and 'width' too. You can the package following the instructions at http://www.braju.com/R/. BTW, I'm sure some would add, so I do it here instead, that it is better to plot density curves, cf. ?density. Cheers Henrik Andreas Wilm wrote: Hi all, I have data which is represented as a histogram and want to add more data / another histogram to this plot using another color. That is I need to superimpose multiple histograms. But have no idea how to do this. Can anybody please give me a hint? Thanks, Andreas __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Row-wise data retrieval
Vasundhara Akkineni wrote: I want to retrieve data row wise from a data frame. My data frame is as below: data-read.table(table.txt, header=TRUE) how can i get row-wise data? Examples: data[1,] data[2,] for (rr in 1:nrow(data)) data[rr,] rows - c(1, 5:8, 3) data[rows,] /Henrik how can i get row-wise data? Thanks, Vasu. [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] Removing Rows
seq() is good at these kind of things: keep - seq(from=1, to=nrow(d), by=10) d1 - d[ keep,] d2 - d[-keep,] /Henrik Juan Pablo Romero wrote: try this: (if d is the data.frame) 1) d[ (1:217)[1:217 %% 10 == 0], ] 2) d[ (1:217)[1:217 %% 10 != 0], ] 2005/11/21, mark salsburg [EMAIL PROTECTED]: I have a data frame with the following dimensions 217 x 5 I want to create two data frames from the original. 1) One containing every tenth row of the original data frame 2) Other containing the rest of the rows. How do I do this? I've tried subset() and calling the index. thank you in advance, [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] writing R shell scripts?
Mike Miller wrote: On Wed, 9 Nov 2005, Henrik Bengtsson wrote: A note of concern: When writing batch scripts like this, be explicit and use the print() statement. A counter example to compare echo 1; 2 | R --slave --no-save and echo print(1); print(2) | R --slave --no-save I guess you are saying that sometimes R will fail if I don't use print(). Can you give an example of how it can fail? This may have been a misunderstanding because it looks like my R and your R are not functioning in the same ways. More below... What I was really try to say is that if you running the R terminal, that is, you sending commands via the R prompt, R will take the *last* value and call print() on it. This is why you get the result when you type 1+1 [1] 2 Without this feature you would have had to type print(1+1) [1] 2 to get any results. Note that it is only the last value calculate, that will be output this way, cf. 1+1; 2+2 [1] 4 My version of R works differently: # echo 1+1; 2+2 | R --slave --no-save [1] 2 [1] 4 It does the same thing from the interactive prompt. This holds in both of these versions of R on Red Hat Linux: R 1.8.1 (2003-11-21). R 2.2.0 (2005-10-06). If I assign the results of earlier computations to variables, then they are not printed: # echo x - 1+1; 2+2 | R --slave --no-save [1] 4 Hmm... You're completely correct. I did not know this, that is, that print() seems to be called by the R terminal also after the completion of each expression and not just newlines. Anyway, my overall message is that you should still be explicit about what you want to output in your code. The following does definitely show what I want to stress: foo - function() { 1+1; 2+2; } foo() [1] 4 and even { 1+1; 2+2; } [1] 4 Or go get the last value calculated by .Last.value, see echo $1; out - .Last.value; write.table(file=stdout(), out, row.names=FALSE, col.names=FALSE); quit() | /usr/local/bin/R --slave --no-save Beautiful. I didn't know about .Last.value, but now that I do, I think we can shorten that script to this... echo $1; write.table(file=stdout(), .Last.value, row.names=FALSE, col.names=FALSE); quit() | /usr/local/bin/R --slave --no-save ...because we no longer need the out variable. It seems like one problem I'm having is that R returns results of every computation, and not just the last one, unless I assign the result to a variable. Example using the doR one-line script above: # doR 'chol(cov(matrix(rnorm(100*5),c(100,5' [,1] [,2][,3] [,4][,5] [1,] 1.021414 0.09806281 0.003275454 0.0009819654 0.05031847 [2,] 0.00 1.10031274 0.002696835 -0.0990352880 0.17356877 [3,] 0.00 0. 0.822075977 -0.0353553332 -0.04559222 [4,] 0.00 0. 0.0 0.9367890692 -0.01513027 [5,] 0.00 0. 0.0 0.00 0.97588119 1.02141394873274 0.0980628119885006 0.00327545419626209 0.000981965434760053 0.050318470112499 0 1.10031274450895 0.00269683530006245 -0.0990352879929318 0.173568771318532 0 0 0.82207597738982 -0.0353553332133034 -0.0455922206141078 0 0 0 0.936789069194909 -0.0151302741201435 0 0 0 0 0.975881188029811 # doR 'x - chol(cov(matrix(rnorm(100*5),c(100,5' 1.09005225946311 0.183719241993361 -0.211250918511775 -0.014827266647 -0.097633753471306 0 0.990599902490968 0.0546812452445389 -0.0255188599622241 0.0502929718369168 0 0 0.982263267444303 -0.0587151164554906 -0.046018923176493 0 0 0 1.00433563628640 0.222340686806836 0 0 0 0 0.976420329786668 I suppose I can live with that. Put everything in curly brackets as my above example show. Is my R really working differently from the R other people are using? No. Sorry about the confusion. Cheers Henrik You may also want to create your own method for returning/outputting data. An ideal way for doing this is to use create a so called generic function, say, returnOutput(), and then special functions for each class of object that you might get returned, e.g. returnOutput.matrix(), returnOutput.list(), etc. Don't forget returnOutput.default(). If you do not understand what I'm talking about here, please read up on S3/UseMethod in R documentation. It's all in there. Then you'll also get a much deeper understanding of how print() (and R) works. Thanks yet again for another great tip! Mike __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] read.table error with R 2.2.0
Florence Combes wrote: Thanks a lot for your answer. In fact I found the solution, it's seems strange to me so I put it here if it could bu useful for other people ... I have the same as you getAnywhere(read.table)$where [1] package:base namespace:base getAnywhere(read.table.default)$where character(0) when I run it in a native R console, and the line : param-read.table(file=param.dat,sep =\t,header=TRUE,fill=TRUE, na.strings=NA) works very well. (I didn't test this before). BUT when I load the aroma package (which I need for what I want to do), then I have : getAnywhere(read.table)$where [1] package:aroma [2] package:base [3] registered S3 method for read from namespace base [4] namespace:base getAnywhere(read.table.default)$where [1] package:aroma registered S3 method for read and the read.table didn't work. So I reinstall the aroma package (even if I had the latest version) and it works well now). best regards, Florence. Hi, author of aroma here. This was fixed a few months ago. From showHistory(aroma): Version: 0.84 [2005-07-01] ... o BUG FIX: GenePixData$read() would give Error in read.table.default(... ...): 5 arguments passed to 'readTableHead' which requires 6. What I have done/did is that I created a read.table.QuantArrayData() function, rename base::read.table() to read.table.default() and made read.table() generic. This should make things rather backward compatible. When I looked at my source code history, the reason for this was: # 2002-08-18 # o Since the 'Measurements' section in QuantArray files seems to contain # rows with tailing TAB's (that just should be ignored) read.table() fails # to read them. read.table() is making use of scan() and scan() has the # argument 'flush' which flushes such trailing cells, but it is not used # by read.table(). For this reason I created the static read.table() # method of QuantArrrayData which has the 'flush' argument. I other words, I just added the argument 'flush=FALSE' to read.table[.QuantArrayData]() and passes 'flush=flush' to its internal calls to scan(). I'll send R-devel a note and see if it is possible to add this argument to the default read.table(). However, everything should work correctly as it is now. Cheers Henrik On 11/9/05, Duncan Murdoch [EMAIL PROTECTED] wrote: On 11/9/2005 10:07 AM, Florence Combes wrote: Dear all, I just upgraded version of R to R 2.2.0, and I have a problem with a script that did not happen with my previous version. Here is the error : - param-read.table(file=param.dat,sep =\t,header=TRUE,fill=TRUE, na.strings=NA) Erreur dans read.table.default(file = param.dat, sep = \t, header = TRUE, : 5 arguments passed to 'readTableHead' which requires 6 - whereas all was OK before. I cannot understand what's happening. Has someone already encountered this ?? Any help greatly appreciated, There is no read.table.default in standard R 2.2.0, so it appears that you have installed a replacement for read.table, and it no longer works. If you type getAnywhere(read.table)$where and getAnywhere(read.table.default)$where you are likely to see where those functions came from. (I see getAnywhere(read.table)$where [1] package:base namespace:base getAnywhere(read.table.default)$where character(0) indicating that read.table comes from the base package, and read.table.default doesn't exist. Duncan Murdoch [[alternative HTML version deleted]] __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] writing R shell scripts?
Mike Miller wrote: Many thanks for the suggestions. Here is a related question: When I do things like this... echo matrix(rnorm(25*2),c(25,2)) | R --slave --no-save ...I get the desired result except that I would like to suppress the [,1] row and column labels so that only the values go to stdout. What is the trick to making that work? What you ask R to do is matrix(rnorm(25*2),c(25,2)) which is equivalent to print(matrix(rnorm(25*2),c(25,2))) What you really want to do might be solved by write.table(), e.g. x - matrix(rnorm(25*2),c(25,2)); write.table(file=stdout(), x, row.names=FALSE, col.names=FALSE); A note of concern: When writing batch scripts like this, be explicit and use the print() statement. A counter example to compare echo 1; 2 | R --slave --no-save and echo print(1); print(2) | R --slave --no-save By the way, I find it useful to have a script in my path that does this: #!/bin/sh echo $1 | /usr/local/bin/R --slave --no-save Suppose that script was called doR, then one could do things like this from the Linux/UNIX command line: # doR 'sqrt(35.6)' [1] 5.966574 # doR 'runif(1)' [1] 0.8881654 Which I find to be handy for quick arithmetic and even for much more sophisticated things. I'd like to get rid of the [1] though! If you want to be lazy and not use, say, doR 'cat(runif(1),\n)' above, maybe a simple Unix sed in your shell script can fix that?! /Henrik Mike __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] writing R shell scripts?
Mike Miller wrote: On Wed, 9 Nov 2005, Henrik Bengtsson wrote: What you really want to do might be solved by write.table(), e.g. x - matrix(rnorm(25*2),c(25,2)); write.table(file=stdout(), x, row.names=FALSE, col.names=FALSE); Thanks. That does what I want. There is one remaining problem for my echo method. While write.table seems to do the right thing for me, R seems to add an extra newline to the output when it closes. You can see that this produces exactly one newline and nothing else: # echo '' | R --slave --no-save | wc -c 1 Is there any way to stop R from sending an extra newline? It's funny because normal running of R doesn't seem to terminate by sending a newline to stdout. Oops -- I just figured it out. If I send quit(), there is no extra newline! Examples that send no extra newline: echo 'quit()' | R --slave --no-save echo x - matrix(rnorm(25*2),c(25,2)); write.table(file=stdout(), x, row.names=FALSE, col.names=FALSE); quit() | R --slave --no-save I suppose we can live with that as it is. Is this an intentional feature? A note of concern: When writing batch scripts like this, be explicit and use the print() statement. A counter example to compare echo 1; 2 | R --slave --no-save and echo print(1); print(2) | R --slave --no-save I guess you are saying that sometimes R will fail if I don't use print(). Can you give an example of how it can fail? What I was really try to say is that if you running the R terminal, that is, you sending commands via the R prompt, R will take the *last* value and call print() on it. This is why you get the result when you type 1+1 [1] 2 Without this feature you would have had to type print(1+1) [1] 2 to get any results. Note that it is only the last value calculate, that will be output this way, cf. 1+1; 2+2 [1] 4 In other words, in the latter example '1+1' is pretty useless and does nothing but taking up CPU time. So, whenever you write batch scripts like yours or standard R scripts called by source(), do use print() explicitly (or cat() or write.table() or ...) if want output! By the way, I find it useful to have a script in my path that does this: #!/bin/sh echo $1 | /usr/local/bin/R --slave --no-save Suppose that script was called doR, then one could do things like this from the Linux/UNIX command line: # doR 'sqrt(35.6)' [1] 5.966574 # doR 'runif(1)' [1] 0.8881654 Which I find to be handy for quick arithmetic and even for much more sophisticated things. I'd like to get rid of the [1] though! If you want to be lazy and not use, say, doR 'cat(runif(1),\n)' above, maybe a simple Unix sed in your shell script can fix that?! It looks like I can rewrite the script like this: #!/bin/sh echo $1 ; write.table(file=stdout(), out, row.names=FALSE, col.names=FALSE); quit() | /usr/local/bin/R --slave --no-save Then I have to always include something like this... out - some_operation ...as part of my command. Example: Or go get the last value calculated by .Last.value, see echo $1; out - .Last.value; write.table(file=stdout(), out, row.names=FALSE, col.names=FALSE); quit() | /usr/local/bin/R --slave --no-save You may also want to create your own method for returning/outputting data. An ideal way for doing this is to use create a so called generic function, say, returnOutput(), and then special functions for each class of object that you might get returned, e.g. returnOutput.matrix(), returnOutput.list(), etc. Don't forget returnOutput.default(). If you do not understand what I'm talking about here, please read up on S3/UseMethod in R documentation. It's all in there. Then you'll also get a much deeper understanding of how print() (and R) works. Please don't ask me to explain it on the mailing list. Cheers Henrik # doR 'A - matrix(rnorm(100*5),c(100,5)); out - chol(cov(A))' 1.08824564637869 0.00749462665482204 -0.109577665309141 0.123824503621501 0.0420504647142321 0 0.969304154505745 0.0689085053799411 0.143273894584171 -0.0204348333174425 0 0 0.995383836907855 0.0860782051613422 0.056980680914183 0 0 0 0.94180592438191 0.0534651651371964 0 0 0 0 0.907266109886987 Now we've got it!! The output above is nice and compact, and it doesn't have an extra newline, but if you want it to look nice on the screen, my friend Stephen Montgomery-Smith (Math, U Missouri) made me this nice little perl script for aligning numbers neatly and easily (but it doesn't work if there are letters in there (e.g., NA or 1.3e-6): http://taxa.epi.umn.edu/misc/numalign # ./doR 'A - matrix(rnorm(100*5),c(100,5)); out - chol(cov(A))' | numalign 0.903339952680364 -0.088773840144205 -0.223677935069773 -0.0736286093726908 0.0457396703130186 0 1.08096548052082 0.0800540640587432 -0.0457840266135511 -0.0311210293661459 0 0 0.938343073536710.0665017259723313 -0.0825698771035788 0 0
Re: [R] warning.expression?
Roger D. Peng wrote: You might be interested in 'tryCatch' to catch warnings. A warning here: tryCatch(expr, warning=...) will catch warnings and interrupt 'expr' (as if an error occured), whereas withCallingHandlers(expr, warning=...) does not do this. /Henrik -roger Thomas Friedrichsmeier wrote: Hi! I'm trying to catch all warning-messages for special handling. It seems options (warning.expression=myfunc ()) can be used for that. However, the question is: How can I get at the actual warning in myfunc ()? Apparently in S, you can use .C(get_last_message) for that. Is there a similar mechanism in R? Thanks for your help! Thomas __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Re: [R] help.search problem
What version of R and what operating system? What packages do you have loaded? Try utils::help.search(tps), does that work? Have you tried it in a fresh R session, i.e. start with R --vanilla. If you can't get it to work after this, report the above information plus what you get from traceback() after you get the error. Cheers Henrik Uzuner, Tolga wrote: Dear Fellow R Users, I have recently come across a weird problem with help.search: help.search(tps) Error in rbind(...) : number of columns of matrices must match (see arg 8) This happens no matter what I search for... Any thoughts ? Thanks, Tolga Please follow the attached hyperlink to an important disclaimer http://www.csfb.com/legal_terms/disclaimer_europe.shtml == Please access the attached hyperlink for an important electronic communications disclaimer: http://www.csfb.com/legal_terms/disclaimer_external_email.shtml __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html __ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html