Re: [R] side-effects in functions that replace object values andattributes
Hi Bill, thanks for your response. There are many cases in which I find direct use of `names-`, `mode-`, `body-`, `[-`, `[[-`, `$-`, etc. to be helpful... so wrapping each function individually seems a bit verbose. Thanks for pointing out the compatibility with S-Plus - that was originally not a concern of mine but I suppose one should keep this in mind. So I propose two solutions, in addition to yours, and wonder if you or others have additional thoughts regarding this issue. Starting with the original problem: x - 1:3 `names-`(x,letters[1:3]) a b c 1 2 3 x a b c 1 2 3 (the modification of the original variable, x, is undesirable - how to prevent it?) --- solution 1) force evaluation within the function environment using force(). (perhaps still not S-Plus friendly) x - 1:3 `names-`(force(x),letters[1:3]) a b c 1 2 3 x [1] 1 2 3 --- solution 2) wrap it in a general function, Funcall(), which will evaluate all arguments into a list before function application. (S-Plus friendly?) Funcall - function(f,...) + do.call(f,list(...)) x - 1:3 Funcall(`names-`,x,letters[1:3]) a b c 1 2 3 x [1] 1 2 3 - Original Message From: William Dunlap wdun...@tibco.com To: Stephen Tucker brown_...@yahoo.com; r-help@r-project.org Sent: Tue, February 16, 2010 5:50:38 PM Subject: RE: [R] side-effects in functions that replace object values andattributes -Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Stephen Tucker Sent: Tuesday, February 16, 2010 5:32 PM To: r-help@r-project.org Subject: [R] side-effects in functions that replace object values andattributes Hello list, I encountered some surprising behavior in R and wanted to check to see if I was imagining things. Previously, I thought that replacement/setter operators in prefix notation (e.g., `[-`(x,1,y) rather than x[1] - y) did not produce side effects (i.e., left 'x' unchanged), but just realized that this is not the case anymore (or has it always been this way? - I don't have access to old R distributions at the moment, but using R 2.10.1 on Ubuntu and OS X)? I went through the NEWS file but did not see a change documented if there was one, but just going by my recollection... In any case, my understanding was that when modifying a value or attribute of an object, R reassigned the modified object to the original symbol. For instance, the help file for `name-`() says that names(z)[3] - c2 is evaluated as z - names-(z, [-(names(z), 3, c2)) But the final (re)assignment (`-`) seems redundant as invisible(names-(z, [-(names(z), 3, c2))) does the same thing. In this case, I wonder if there is a preferred way to use the replacement/setter operators in prefix notation without producing such side effects I would never recommend using replacement operators this way. In part this is because S+ doesn't like it: S+ x-1:10 S+ `[-`(x, 1, value=66.6) [1] 66.6 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 Warning messages: looks like the internal reference count was not updated in: x[1] - 66.6 S+ x [1] 1 2 3 4 5 6 7 8 9 10 in part because it is ugly, but mostly it is because forcing the program to accept such usage closes off, or at least restricts, an avenue for saving memory when doing replacement operations. If you have a replacement function that you are tempted to use in this way, I recommend that you write a wrapper function for it. E.g., instead of using namedX - `names-`(x, value=as.character(x)) write setNames - function(x, names) { names(x) - names x } and use it as namesX - setNames(x, as.character(x)) Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com (replace() exists for `[-`() and `[[-`(), but perhaps something more general). For instance, if I did not desire the following modification in x: x - c(1,2) y - `names-`(x,c(a,b)) y a b 1 2 x a b 1 2 I might take advantage of R's lazy evaluation and use create a copy in the local function environment and allow that copy to be modified: x - c(1,2) y - `names-`(`-`(x,x),c(a,b)) y a b 1 2 x [1] 1 2 The interesting thing is that `mode-`(), while also a setter function in that it sets an object attribute, does not behave as `names-`(): x - c(1,2) y - `mode-`(x,integer) y [1] 1 2 x [1] 1 2 mode(x) [1] character So another question that naturally arises is whether there a general rule by which we can predict the behavior of these types of operators (whether they produce side effects or not)? Thanks, Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code
[R] side-effects in functions that replace object values and attributes
Hello list, I encountered some surprising behavior in R and wanted to check to see if I was imagining things. Previously, I thought that replacement/setter operators in prefix notation (e.g., `[-`(x,1,y) rather than x[1] - y) did not produce side effects (i.e., left 'x' unchanged), but just realized that this is not the case anymore (or has it always been this way? - I don't have access to old R distributions at the moment, but using R 2.10.1 on Ubuntu and OS X)? I went through the NEWS file but did not see a change documented if there was one, but just going by my recollection... In any case, my understanding was that when modifying a value or attribute of an object, R reassigned the modified object to the original symbol. For instance, the help file for `name-`() says that names(z)[3] - c2 is evaluated as z - names-(z, [-(names(z), 3, c2)) But the final (re)assignment (`-`) seems redundant as invisible(names-(z, [-(names(z), 3, c2))) does the same thing. In this case, I wonder if there is a preferred way to use the replacement/setter operators in prefix notation without producing such side effects (replace() exists for `[-`() and `[[-`(), but perhaps something more general). For instance, if I did not desire the following modification in x: x - c(1,2) y - `names-`(x,c(a,b)) y a b 1 2 x a b 1 2 I might take advantage of R's lazy evaluation and use create a copy in the local function environment and allow that copy to be modified: x - c(1,2) y - `names-`(`-`(x,x),c(a,b)) y a b 1 2 x [1] 1 2 The interesting thing is that `mode-`(), while also a setter function in that it sets an object attribute, does not behave as `names-`(): x - c(1,2) y - `mode-`(x,integer) y [1] 1 2 x [1] 1 2 mode(x) [1] character So another question that naturally arises is whether there a general rule by which we can predict the behavior of these types of operators (whether they produce side effects or not)? Thanks, Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Compose in roxygen - order of function application?
Hello, I wonder if anyone has used the Compose() function in the 'roxygen' package. I find its behavior a bit surprising: f - function(x) x + 1 g - function(x) x * 2 f(g(2)) [1] 5 Compose(f,g)(2) [1] 6 g(f(2)) [1] 6 Compose(g,f)(2) [1] 5 I would have expected Compose(f,g)(x) == f(g(x)) but it appears the order of application is reversed. It would be easy for me to modify with rev(): Compose - function (...) { fs - rev(list(...)) function(...) Reduce(function(x, f) f(x), fs, ...) } But does the current implementation follow another convention I am unaware of? Thanks - Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Merge data frames but with a twist.
You may want to use the reshape package for this task: library(reshape) recast(DF3,Show ~ Datetime, id.var=names(DF3),value=Measure) Show 08/26/2009 11:30 AM 08/26/2009 9:30 AM 1 Firefly 3 1 2 Red Dwarf 4 2 If you want to plot time series, you can do something like the following mydf - .Last.value ## save the output from above to mydf library(zoo) zobj - zoo(`mode-`(t(mydf),numeric), as.chron(strptime(names(mydf)[-1],%m/%d/%Y %I:%M %p))) plot(zobj) (zobj is a time series object of the zoo class) - Original Message From: Tony Breyal tony.bre...@googlemail.com To: r-help@r-project.org Sent: Thursday, August 27, 2009 4:04:30 AM Subject: [R] Merge data frames but with a twist. Dear all, Question: How to merge two data frames such that new column are added in a particular way? I'm not actually sure how to best articulate my question to be honest, so i hope showing you what I want to achieve will communicate my question better. Lets say I have two data frames: DF1 - data.frame(cbind(Show=c('Firefly', 'Red Dwarf'), Measure=1:2, Datetime=c('08/26/2009 9:30 AM', '08/26/2009 9:30 AM'))) DF2 - data.frame(cbind(Show=c('Firefly', 'Red Dwarf'), Measure=3:4, Datetime=c('08/26/2009 11:30 AM', '08/26/2009 11:30 AM'))) And then let us merge these: DF3 - merge(DF1, DF2, all=TRUE) Show MeasureDatetime 1 Firefly 1 08/26/2009 9:30 AM 2 Firefly 3 08/26/2009 11:30 AM 3 Red Dwarf 2 08/26/2009 9:30 AM 4 Red Dwarf 4 08/26/2009 11:30 AM What i would like to do is merge the data frames such that i end up with the following: Show 08/26/2009 9:30 AM08/26/2009 11:30 AM Firefly 13 Red Dwarf24 my reason for doing this is so that i can plot a time series somehow. I hope the formating stays when i post this message and that what i'm trying to do is easy to understand. Thank you kindly for any help in advance. Tony __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Merge data frames but with a twist.
Ah, thanks always - I originally thought as.chron() was required to have all fields (m/d/y hh:mm:ss) as for chron() but I see that the former passes its 'format' argument to as.POSIXct() Good deal! Stephen - Original Message From: Gabor Grothendieck ggrothendi...@gmail.com To: Stephen Tucker brown_...@yahoo.com Cc: Tony Breyal tony.bre...@googlemail.com; r-help@r-project.org Sent: Thursday, August 27, 2009 7:27:26 AM Subject: Re: [R] Merge data frames but with a twist. On Thu, Aug 27, 2009 at 9:55 AM, Stephen Tuckerbrown_...@yahoo.com wrote: You may want to use the reshape package for this task: library(reshape) recast(DF3,Show ~ Datetime, id.var=names(DF3),value=Measure) Show 08/26/2009 11:30 AM 08/26/2009 9:30 AM 1 Firefly 3 1 2 Red Dwarf 4 2 If you want to plot time series, you can do something like the following mydf - .Last.value ## save the output from above to mydf library(zoo) zobj - zoo(`mode-`(t(mydf),numeric), as.chron(strptime(names(mydf)[-1],%m/%d/%Y %I:%M %p))) plot(zobj) (zobj is a time series object of the zoo class) Note that as.chron can take % codes directly so the as.chron portion can be shortened to: as.chron(names(mydf)[-1],%m/%d/%Y %I:%M %p) __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] concatenating multiple columns from files
You can do something like mat - do.call(cbind, lapply(list.files(.data),read.table)) ## explanation: lapply(list.files(.data),read.table) will store all tables in a list do.call(cbind,...) will bind all the columns stored in the list created above. - Original Message From: ferreirafm ferreir...@lim12.fm.usp.br To: r-help@r-project.org Sent: Thursday, July 30, 2009 5:29:46 PM Subject: [R] concatenating multiple columns from files R-users, I want to concatenate columns from different files in a single object. I'm doing bad. My peace of code is as follow: rawdata - list.files(./data) for (i in rawdata) { mat[ ] - read.table(paste(i ,sep=)) } At the end of the loop I have just one column. What I'm doing wrong? Thanks, Fred -- View this message in context: http://www.nabble.com/concatenating-multiple-columns-from-files-tp24748542p24748542.html Sent from the R help mailing list archive at Nabble.com. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] PDF Compression
There was a previous post about this also: http://tolstoy.newcastle.edu.au/R/e2/help/07/05/17475.html I was able to use bitmap(,type=pdfwrite) on Ubuntu Linux but had trouble getting it to work on Windows. For now, it's kind of kludgey but I have in my .Rprofle (or .Rprofile.site on Windows): compressPDF - function(x) { system(paste(pdftk,x,output,sub(\\.pdf,c.pdf,x), compress dont_ask)) unlink(x) } so after I plot something I would call compressPDF() on the same pdf file pdf(plot.pdf); plot(1:10); dev.off() compressPDF(plot.pdf) which renames it from 'plot.pdf' to 'plotc.pdf' to remind myself that I already compressed it... __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] R_LIBS in Windows Vista
Hello, I am trying to install R and have it running through ESS on a Vista machine that is not mine (I am only familiar with Windows XP and Ubuntu Linux) so please pardon my unfamiliarity... The Rgui.exe installation works fine and package installation also appears to work fine. The base packages are installed in C:/Program Files/R/R-2.8.0/library/ and user-installed packages are installed in C:/Users/Name/Documents/R/win-library/2.8/ When I run R with Rgui.exe, everything appears to run fine, and I can load the libraries. When I try to run R through ESS, I get library(chron) ...library not found error and library(chron,lib.loc=C:/Users/Name/Documents/R/win-library/2.8/) still same problem, though chron/ is indeed located in C:/Users/Name/Documents/R/win-library/2.8/ I looked at the R Windows FAQ and decided to check Sys.getenv(R_LIBS_USER) and it's not C:/Users/Name/Documents/R/win-library/2.8/ but instead C:/Users/Name/AppData/R/win-library/2.8/ (I think, trying to recall from memory as it is not my machine) So as instructed in the FAQ I did dir.create(Sys.getenv(R_LIBS_USER), recursive = TRUE) and tried reinstalling chron with install.packages() but was denied permission. I also: 1) created Renviron.site (and also .Renviron) and set R_LIBS=C:/Users/Name/Documents/R/win-library/2.8/ as suggested in the R FAQ, but I could neither load from or write to this directory. 2) I tried Sys.setenv(R_LIBS_USER=C:/Users/Name/Documents/R/win-library/2.8/) but also no luck... I wonder if anyone has further suggestions? Thanks very much, Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] behavior of squishplot in TeachingDemos
Hi list, I wonder if anyone has had this experience with squishplot() in the TeachingDemos package. Taking the example from the ?image help page, library(TeachingDemos) x - 10*(1:nrow(volcano)) y - 10*(1:ncol(volcano)) layout(matrix(c(1,2,3,4),ncol=2,byrow=TRUE),height=c(2,1)) ## 1st plot op - squishplot(range(x),range(y),1) image(x, y, volcano, col = terrain.colors(100)) par(op) ## 2nd plot op - squishplot(range(x),range(y),1) image(x, y, volcano, col = terrain.colors(100)) par(op) The second plot comes out looking as expected, but the first plot is not squished in the desired proportions. I tried tracking the modifications to par('pin') and par('plt') in the function but gave up midway through in desire for haste - not sure what is going on but I did find that taking advantage of the behavior above, calling plot.new(); par(new=TRUE) before the first plot makes things work as expected. So the full code would be layout(matrix(c(1,2,3,4),ncol=2,byrow=TRUE),height=c(2,1)) ## 1st plot op - squishplot(range(x),range(y),1) plot.new() par(new=TRUE) image(x, y, volcano, col = terrain.colors(100)) par(op) ## 2nd plot op - squishplot(range(x),range(y),1) image(x, y, volcano, col = terrain.colors(100)) par(op) +++ I wonder if this behavior is not surprising? It is a great function overall though - thanks for the contribution. Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] importing data to SQLite database with sqldf
Hi all, I am attempting to learn SQL through sqldf... One task I am particularly interested in is merging separate (presumably large) files into a single table without loading these files into R as an intermediate step (by loading them into SQLite and merging them there). Taking a step back, I've considered these alternatives: 1) I know if I use straight SQLite commands I might use the 'IMPORT' or 'INSERT INTO' command, which is not terribly flexible... (I can read large files line-by-line in Python and use the 'INSERT INTO' command, which is reasonably fast; I could do this in R as well but my experience with R's input/output is that it's much slower...? and sometimes setting up the table column definitions can be tedious if there are many variables). 2) dbWriteTable() with append=TRUE is very convenient except that it requires I load the data into R first... 3) sqldf's capability to put data directly into a database is something I'd like to work out. So in this case I have a series of tab-delimited text file with the first line being a header. For some reason I cannot seem to get it working. Combining examples 6 and 9 from the Google Code page (and R-help archives), I tried source(http://sqldf.googlecode.com/svn/trunk/R/sqldf.R;) (do I need it for SQLite?) ## sqldf(attach 'mydb.db' as new) f - file(myexample.txt) attr(f,file.format) - list(header=TRUE,sep=\t) sqldf(create table myexample as select * from f, stringsAsFactors=FALSE, dbname=mydb.db) ## or f - file(fi) sqldf(create table myexample as select * from f, stringsAsFactors=FALSE,file.format=list(header=TRUE,sep=\t), dbname=mydb.db) ## sqldf(select * from myexample,dbname=mydb.db) gives me tables with 0 rows and 0 columns... So in any case I have a few questions: === 1 Would this be scalable to files with few GBs of data in them (I guess I am uncertain of the underlying mechanism for transporting data from the .txt file to the .db file... I see there is a call the dbWriteTable() internally in sqldf but through the connection)? And is there anything obviously doing wrong above? === 2 === Since I cannot 'append' rows to existing tables in SQLite (or any SQL database), I think what I would have to do is to load each of the files into the database and then 'rbind' them into a new table using 'union all'? The following code is what I have (the part where I read in each file before dumping into the database file would hopefully be replaced by the method above, if it can be made to work). ## (1) create a database file sqldf(attach 'alltables.db' as new) ## (2) convenience function sql - function(...) sqldf(...,dbname=alltables.db) ## (3) load data as separate tables for( fi in list.files(.,txt$) ) { mydata - read.delim(fi) sql(sprintf(create table %s as select * from mydata,sub(\\.txt,,fi))) } rm(fi,mydata) ## (4) merge tables tablenames - as.character(sql(select * from sqlite_master)$name) sql(paste(create table myfulltable as, paste(sprintf(select * from %s,tablenames), collapse= union all ))) ## (5) delete separate tables since we have a merged one for( nm in tablenames ) sql(sprintf(drop table %s,nm)) === 3 === The following command sqldf(attach 'mydb.db' as new) DF - read.delim(fi) sqldf(create table myexample as select * from DF,dbname=mydb.db) will usually create a .db file twice the size of the .txt file (for now I am playing with a files ~500KB so the .db files are around ~1MB). When I create a .db file using SQLite's 'import' command, RSQLite's dbWriteTable(), or inserting values from the same .txt file from Python's SQLite interface, I get .db files that are approximately the same size as the .txt file (~500KB). Is the larger file size for sqldf's method expected? Many thanks in advance! Stephen Tucker __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] plot order in multi-panel figure
Hi, Does anyone know if there is a way to 'reset the plot number' on a traditional graphics device? For instance, I want to have two plots on stacked top of each other (mfrow=c(2,1)) but with underlying grid lines spanning both figures vertically. I can put the grid lines on top if I add them last: par(mfrow=c(2,1)) plot.new() plot.window(c(0,1),c(0,1)) for( i in 1:2) axis(i) box(bty=L) rect(0.2,0.2,0.5,0.5,col=8) plot.new() plot.window(c(0,1),c(0,1)) for( i in 1:2) axis(i) box(bty=L) par(mfrow=c(1,1)) plot.window(c(0,1),c(0,1)) abline(v=seq(0,1,by=0.2),lty=3) But ideally I would like to draw the grid lines before drawing other objects on top of it, but something like par(mfrow=c(1,1)) plot.new() plot.window(c(0,1),c(0,1)) abline(v=seq(0,1,by=0.2),lty=3) par(mfrow=c(2,1)) plot.window(c(0,1),c(0,1)) for( i in 1:2) axis(i) box(bty=L) rect(0.2,0.2,0.5,0.5,col=8) plot.new() plot.window(c(0,1),c(0,1)) for( i in 1:2) axis(i) box(bty=L) does not work because the first of the two plots appears in the bottom of the figure and not the top (as it is interpreted as the second of the mfrow=c(2,1) plots). I've also played around with layout() but I also get the same behavior. I suspect I can do this eventually with grid graphics but was wondering if it is also possible in traditional graphics. I would appreciate any help - thanks very much! Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Pdf file size for very scatter plots
I thought running it through latex will compress the pdf - but this post nicely summarizes some options: http://tolstoy.newcastle.edu.au/R/e2/help/07/05/17475.html I personally prefer the pdftk approach* over the ghostscript option** as the latter seems to give me a number of problems on Windows XP. *if you install pdftk (and put it in your search path), after you create filename.pdf with pdf(), do pdftk filename.pdf cat output newfilename.pdf compress or pdftk filename.pdf cat output newfilename.pdf compress dont_ask **if you have ghostview installed (and in your search path), bitmap(filename.pdf,type=pdfwrite) plot(...) dev.off() - Original Message From: Nazareno Andrade [EMAIL PROTECTED] To: r-help r-help@r-project.org Sent: Friday, August 15, 2008 12:46:52 PM Subject: Re: [R] Pdf file size for very scatter plots Jim, Thanks for the answer. Using pch=. reduces the file to ~3MB... Still large. I'll look into hexbins, but if I understand it right, it would 'round' points which are nearby into a same hexagon, right? Couldn't that result in an inaccurate view of a scatter plot? Here's the code I'm using: pdf(); plot(rnorm(1e5), rnorm(1e5), pch = .); dev.off() thanks again, Nazareno On Fri, Aug 15, 2008 at 12:27 PM, jim holtman [EMAIL PROTECTED] wrote: Have you tried using pch='.'? Also you might consider using 'hexbin' for creating the scatter plot. On Fri, Aug 15, 2008 at 12:24 PM, Nazareno Andrade [EMAIL PROTECTED] wrote: Dear all, I am plotting a scatter plot for a large sample (1e+05 ordered pairs). This produces a large (~5MB) file in a pdf or postscript terminal, and I am wondering whether there are methods for reducing the size of the resulting file so that it is easier to include it in a document. I'd rather stick with pdf or ps as I am using latex. thanks, Nazareno __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve? __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] tryCatch question
Hi Kevin, I learned to use tryCatch() from this page: http://www1.maths.lth.se/help/R/ExceptionHandlingInR/ Hope this helps, ST - Original Message From: Luke Tierney [EMAIL PROTECTED] To: [EMAIL PROTECTED] Cc: r-help@r-project.org Sent: Thursday, August 14, 2008 8:59:35 AM Subject: Re: [R] tryCatch question Read the argment descriptions and Look at the examples in ?tryCatch. The `expr' argument (i.e. the code to try) and the `finally' argument are expressions that are evaluated (via standard lazy evaluation of arguments). The error condition handlers, provided as the `...' argument in errorClass = handler form(s), are functions of one argument, the error condition. As in the examples I usualy use fuctions writen in-line. There is no non-standard evaluation involved, so standard scoping rules apply. luke On Thu, 14 Aug 2008, [EMAIL PROTECTED] wrote: I would like to use the 'tryCatch' function but am having a hard time getting my head around it. In 'C' like languages try/catch/finally means try a block of statements and if any throw an error then do the statements in the catch block and then error or not always do the staements in the finally block. In 'R' as best as I can tell the block of staements in the try block is a single function. Does this mean I need to construct a temporary function that contains what I would have put in the try blck? Also in 'R' it seems the 'finally' function (of 'tryCatch' most closely mimics the catch block of 'C'. Right? A similar comment on the finally function. Do I need to create a temporary function that contains the staements that I normally would put in a 'C' like catch clause? If I do need to create functions for the try and error conditions what is the scope or enviironment that the functions are called under? The 'try' function is relatively straightforward but when an error occurs what variable will I have access to? Thank you. Kevin __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- Luke Tierney Chair, Statistics and Actuarial Science Ralph E. Wareham Professor of Mathematical Sciences University of Iowa Phone: 319-335-3386 Department of Statistics andFax: 319-335-3017 Actuarial Science 241 Schaeffer Hall email: [EMAIL PROTECTED] Iowa City, IA 52242 WWW: http://www.stat.uiowa.edu __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] levels values of cut()
Not sure what you're looking for, but does this help? Extending your code, library(gsubfn) t(strapply(levels(my.cuts),([0-9.]+),([0-9.]+), + function(...) as.numeric(c(...)),backref=-2,simplify=TRUE)) [,1] [,2] [1,] 15.9 38.3 [2,] 38.3 60.7 [3,] 60.7 83.1 - Original Message From: baptiste auguie [EMAIL PROTECTED] To: r-help@r-project.org Sent: Saturday, August 9, 2008 1:51:01 AM Subject: [R] levels values of cut() Dear list, I have the following example, from which I am hoping to retrieve numeric values of the factor levels (that is, without the brackets): x - seq(1, 15, length=100) y - sin(x) my.cuts - cut(which(abs(y) 1e-1), 3) levels(my.cuts) hist() does not suit me for this, as it does not necessarily respect the number of breaks. getAnywhere hasn't got me very far: I cannot seem to find a readable code for the built-in cut function in the base library. I think getMethod should do it but I don't understand the arguments to pass. Any pointers appreciated, Thanks, baptiste _ Baptiste Auguié School of Physics University of Exeter Stocker Road, Exeter, Devon, EX4 4QL, UK Phone: +44 1392 264187 http://newton.ex.ac.uk/research/emag __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Extract Element of String with R's Regex
In the example below, a straight application of strsplit() is probably the simplest solution. In a more general case where it may be desirable to match patterns, a combination of sub() or gsub() with strsplit() might do the trick: x - Best-K Gene 11340 211952_at RANBP5 Noc= 3 - 2 LL= -963.669 -965.35 patt - Best-K Gene \\d+ (\\w+) (\\w+) Noc= \\d - (\\d) LL= (.*) unlist(strsplit(gsub(patt,\\1,\\2,\\3,x,perl=TRUE),,)) [1] 211952_at RANBP52 Alternatively, you may want to take a look at the gsubfn package - it is quite useful. Still learning to use it myself... library(gsubfn) unlist(strapply(x,patt,function(x1,x2,x3) c(x1,x2,x3),backref=-3,perl=TRUE)) [1] 211952_at RANBP52 - Original Message From: Simon Blomberg [EMAIL PROTECTED] To: Edward Wijaya [EMAIL PROTECTED] Cc: r-help@r-project.org Sent: Thursday, July 31, 2008 11:48:23 PM Subject: Re: [R] Extract Element of String with R's Regex How about: unlist(strsplit(x, split= ))[c(4:5,10)] That perl script looks like a good reason to avoid perl. Simon. On Fri, 2008-08-01 at 15:13 +0900, Edward Wijaya wrote: Hi, I have this string, in which I want to extract some of it's element: x - Best-K Gene 11340 211952_at RANBP5 Noc= 3 - 2 LL= -963.669 -965.35 yielding this array [1] 211952_at RANBP5 2 In Perl we would do it this way: __BEGIN__ my @needed =(); my $str = Best-K Gene 11340 211952_at RANBP5 Noc= 3 - 2 LL= -963.669 -965.35; $str =~ /Best-K Gene \d+ (\w+) (\w+) Noc= \d - (\d) LL= (.*)/; push @needed, ($1,$2,$3); __END___ How can we achieve this with R? - E.W. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- Simon Blomberg, BSc (Hons), PhD, MAppStat. Lecturer and Consultant Statistician Faculty of Biological and Chemical Sciences The University of Queensland St. Lucia Queensland 4072 Australia Room 320 Goddard Building (8) T: +61 7 3365 2506 http://www.uq.edu.au/~uqsblomb email: S.Blomberg1_at_uq.edu.au Policies: 1. I will NOT analyse your data for you. 2. Your deadline is your problem. The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data. - John Tukey. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] chron objects: input/output
Hi list, I have some questions regarding 1) conversion of date + time characters to chron 2) formatting chron object printing Regarding (1), Gabor's Rnews 2004 4/1 article has been indispensible, but I often work with files where dates and times are contained in a single field. In this case, I would like to control input/output of chron objects when each observation of date and time is stored as a single string. So here are some procedures that I've tried: ## define character vector x - c(07/01/2001 12:00:00,07/17/2001 15:00:00) ## method 1 library(chron) chron(substring(x,1,10),substring(x,12)) [1] (07/01/01 12:00:00) (07/17/01 15:00:00) ## method 2 (recently inspired by Gabor's post) do.call(c,strapply(x,(.*) (.*),chron,backref=-2)) [1] (07/01/01 12:00:00) (07/17/01 15:00:00) ## method 3 (chronObj - as.chron(strptime(x,%m/%d/%Y %T))) [1] (07/01/01 12:00:00) (07/17/01 15:00:00) Could there be any gotchas with the third method (as.chron(strptime(...)))? The 'tz' attribute for POSIXlt objects are ignored, but I am not sure if there are any implications of the '$isdst' field are for conversions. I do like this alternative for the conciseness-flexibility tradeoff; in my experience, I have not had any problems - but wanted to inquire if at some point the '$isdst' field (or possibly something else) could give me trouble. Regarding the printing of chron objects, this behavior is peculiar to me: format(chronObj,format=c(m/d,h:m)) [1] (0701 1200) (0717 1500) The special characters (/,:) are not printed - I've tried changing the attribute of the chron object, looked at the format.chron() method (getS3method(format,chron)), etc. and am still confused; the chron() documentation says its specification should be similar the input format. Could I have missed something? Thanks! ST __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Colors in Sweave
From: Duncan Murdoch murdoch_at_stats.uwo.ca Date: Tue, 29 Jul 2008 19:45:28 -0400 On 27/07/2008 3:10 PM, Stephen Tucker wrote: Hi list, I was using Sweave and was wondering if anyone has had any luck changing the font colors of the code chunks. For instance, in my .Rnw preample I tried including: === \usepackage[usenames]{colors} \definecolor{darkred}{rgb}{0.545,0,0} \definecolor{midnightblue}{rgb}{0.098,0.098,0.439} \DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl,formatcom={\color{midnightblue}}} \DefineVerbatimEnvironment{Soutput}{Verbatim}{formatcom={\color{darkred}}} \DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl,formatcom={\color{blue}}} === which works in the sense that colors do show up in the processed pdf document, but extra spaces in between the input and output code chunks appear (which is not the case when colors are not specified), resulting in a long document with many blank lines. Alternatively, in the resulting tex document I replaced all instances of \begin{Sinput}... \end{Sinput} with {\color{midnightblue}\begin{Sinput} ... \end{Sinput}} and darkred for Soutput and so on. When I do this, I get the following error message: === LaTeX excerpt === \begin{Schunk} {\color{midnightblue}\begin{Sinput} ISOdatetime(1970, 1, 1, 0, 0, 0, ) - ISOdatetime(1970, 1, 1, + 0, 0, 0, GMT) \end{Sinput}} {\color{darkred}\begin{Soutput} Time difference of 8 hours \end{Soutput}} \end{Schunk} === === error message === ) ! FancyVerb Error: Extraneous input `}\end{}' between \end{Sinput} and line end . \FV_at_Error ... {FancyVerb Error: \space \space #1 } l.13 \end{Sinput}} === I guess I don't know enough of the Schunk/Sinput/Soutput definitions to toy with it and was wondering if anyone had tried something similar. The definitions are very simple: see Sweave.sty, they're just \DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl} \DefineVerbatimEnvironment{Soutput}{Verbatim}{} \DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl} \newenvironment{Schunk}{}{} I would use \DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl,formatcom=\color{midnightblue}} (i.e. no extra braces), but whether or not I do that, I don't notice extra spacing beyond what Sweave always puts in. To get rid of the usual Sweave extra spacing, try \fvset{listparameters={\setlength{\topsep}{0pt}}} \renewenvironment{Schunk}{\vspace{\topsep}}{\vspace{\topsep}} Duncan Murdoch = Hi Duncan, For some reason I never saw your response until now but this is great! Thanks - incidentally, I realized it was something to do with either the color or fancyvrb package so I posted a question to the latex help list and got a helpful response. Essentially, the idea would be to combine both S input and output into a single Verbatim environment and change the colors within it (requires fancyvrb package which Sweave uses): \renewcommand{\FancyVerbFormatLine}[1]{% \ifnum\value{FancyVerbLine}5\color{red}#1% \else\color{blue}#1\fi} \begin{Verbatim} line 1 line 2 line 3 line 4 line 5 line 6 line 7 \end{Verbatim} However, in the context of the Sweave application, your solution is elegant and simpler than processing the entire document and replacing all \begin{Sinput}...\end{Sinput}, \begin{Soutput}...\end{Soutput} instances with the \renewcommand and Verbatim environement calls. Thanks very much, Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Storing Matrices into Hash
Hm didn't know about the abind package. That is pretty sweet. I do often opt for the 'list of matrices' myself though because I'm more familiar with the methods for lists... To answer one of Gundala's questions directly (assuming list of matrices is acceptable): Since you can do this, x - list() x[[a]] - 1 x[[b]] - 2 x $a [1] 1 $b [1] 2 You should be able to do this as well: all_mat - list() for (matno in 1:10) { all_mat[[paste(mat,matno,sep=)]] - process_to_create_matrix(da[matno]) } and refer to mat$mat_no etc. - Original Message From: Bert Gunter [EMAIL PROTECTED] To: Erik Iverson [EMAIL PROTECTED]; Gundala Viswanath [EMAIL PROTECTED] Cc: [EMAIL PROTECTED] Sent: Thursday, July 31, 2008 7:56:49 PM Subject: Re: [R] Storing Matrices into Hash R also has arrays (?array). If all the matrices are the **same dimension** and **same mode** (i.e. all numeric or all character), this is perhaps easier, especially if you want to access various pieces of your matrices. Given existing matrices, mat1, mat2,..., the slightly tricky way to combine them into an array is: your_array - array(c(mat1,mat2,..),dim=c(dim(mat1,n)) ## where n is the number of matrices. This is slightly tricky because you have to understand that matrices are actually vectors in column major order with a dim attribute. An easier way to do it is to install the abind package from CRAN and just do your_array - abind(mat1,mat2, ..., along =3) Accessing the matrices is then easy using array indexing. Again, this is only possible if they're all the same dimension. Otherwise Erik's approach must be used. I recommend that you spend some time learning about R's data structures. R's internal documentation, especially An Intro to R, is a good starting point, but there are now many books, both in English and other major European languages, out there to help you. The CRAN website lists many of them. Cheers, Bert Gunter Genentech, Inc. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Erik Iverson Sent: Thursday, July 31, 2008 7:01 PM To: Gundala Viswanath Cc: [EMAIL PROTECTED] Subject: Re: [R] Storing Matrices into Hash I think a named list is probably the easiest way to start off, something like: all_mat - list(mat1 = mat1, mat2 = mat2) all_mat$mat2 Gundala Viswanath wrote: Hi, Suppose I have these two matrices (could be more). What I need to do is to store these matrices into a hash. So that I can call back any of the matrix back later. Is there a way to do it? mat_1 [,1][,2] [1,] 9.327924e-01 0.067207616 [2,] 9.869321e-01 0.013067929 [3,] 9.892814e-01 0.010718579 [4,] 9.931603e-01 0.006839735 [5,] 9.149056e-01 0.08509 mat_2 [,1][,2] [1,] 9.328202e-01 0.067179769 [2,] 9.869402e-01 0.013059827 [3,] 9.892886e-01 0.010711437 [4,] 9.931660e-01 0.006833979 [5,] 9.149391e-01 0.085060890 This method I have is not favorable because it just stack the matrices together as another matrix. Makes it hard to get individual matrix later. all_mat - NULL all_mat - c(all_mat, mat1,mat2) - Gundala Viswanath Jakarta - Indonesia __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Colors in Sweave
Hi list, I was using Sweave and was wondering if anyone has had any luck changing the font colors of the code chunks. For instance, in my .Rnw preample I tried including: === \usepackage[usenames]{colors} \definecolor{darkred}{rgb}{0.545,0,0} \definecolor{midnightblue}{rgb}{0.098,0.098,0.439} \DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl,formatcom={\color{midnightblue}}} \DefineVerbatimEnvironment{Soutput}{Verbatim}{formatcom={\color{darkred}}} \DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl,formatcom={\color{blue}}} === which works in the sense that colors do show up in the processed pdf document, but extra spaces in between the input and output code chunks appear (which is not the case when colors are not specified), resulting in a long document with many blank lines. Alternatively, in the resulting tex document I replaced all instances of \begin{Sinput}... \end{Sinput} with {\color{midnightblue}\begin{Sinput} ... \end{Sinput}} and darkred for Soutput and so on. When I do this, I get the following error message: === LaTeX excerpt === \begin{Schunk} {\color{midnightblue}\begin{Sinput} ISOdatetime(1970, 1, 1, 0, 0, 0, ) - ISOdatetime(1970, 1, 1, + 0, 0, 0, GMT) \end{Sinput}} {\color{darkred}\begin{Soutput} Time difference of 8 hours \end{Soutput}} \end{Schunk} === === error message === ) ! FancyVerb Error: Extraneous input `}\end{}' between \end{Sinput} and line end . [EMAIL PROTECTED] ... {FancyVerb Error: \space \space #1 } l.13 \end{Sinput}} === I guess I don't know enough of the Schunk/Sinput/Soutput definitions to toy with it and was wondering if anyone had tried something similar. Thanks! Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Object-oriented programming in R for Java programmers?
I've never used it myself but I recall reading about this R.oo package a while ago - might be worth considering? http://www1.maths.lth.se/help/R/R.oo/ - Original Message From: Werner Wernersen [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Sunday, July 27, 2008 4:55:26 AM Subject: [R] Object-oriented programming in R for Java programmers? Hi, I was wondering if anybody might have a reference for me: My R code is growing and getting more and more confusing. Thus, I figure it's time to switch to object-oriented again. I have done oo programming in C++ and Java before but the first few tutorial on R oo were a bit confusing for me. Is there any brief tutorial on oo programming in R especially for people who have done oo in Java or C++ before? That would be really helpful. Many thanks and have a great Sunday, Werner __ Dem pfiffigeren Posteingang. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Object-oriented programming in R for Java programmers?
This page is also a brief introduction to the S3 classes: http://www.ibm.com/developerworks/linux/library/l-r3.html (see section on 'Object-oriented R') and for S4, in addition to How S4 methods work: http://developer.r-project.org/methodDefinition.html - Original Message From: Johannes Huesing [EMAIL PROTECTED] To: r-help@r-project.org Sent: Sunday, July 27, 2008 12:21:37 PM Subject: Re: [R] Object-oriented programming in R for Java programmers? Werner Wernersen [EMAIL PROTECTED] [Sun, Jul 27, 2008 at 01:55:26PM CEST]: [...] Is there any brief tutorial on oo programming in R especially for people who have done oo in Java or C++ before? That would be really helpful. How S4 methods work highlights the differences between R's function-centric approach to OO and the class-centric approach highlighted by languages such as C++. This 10-page article is written by John Chambers. -- Johannes Hüsing There is something fascinating about science. One gets such wholesale returns of conjecture mailto:[EMAIL PROTECTED] from such a trifling investment of fact. http://derwisch.wikidot.com (Mark Twain, Life on the Mississippi) __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] help with data layout
Hi, hope this will help: txt - Col1,Col2 A,3 , 2 ,3 B,4 , 5 , 4 C,1 , 4 , 3 ## read data dat - read.csv(textConnection(txt),na.string=) ## fill in empty cells with correct category dat$Col1[] - Reduce(function(x,y) c(x,ifelse(is.na(y),tail(x,1),y)),dat$Col1) ## calculate mean and standard deviation mat - t(sapply(split(dat$Col2,f=dat$Col1),function(X) c(mean=mean(X),sd=sd(X ## look at results (stored in a matrix) print(mat) meansd A 2.67 0.5773503 B 4.33 0.5773503 C 2.67 1.5275252 - Original Message From: Iain Gallagher [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Thursday, July 17, 2008 8:50:42 AM Subject: [R] help with data layout Hello list I have been given some Excel sheets with data laid like this: Col1Col2 A 3 2 3 B 4 5 4 C 1 4 3 I was hoping to import this into R as a csv and then get the mean and SD for each letter in column 1. Could someone give me some guidance on best to approach this? Thanks Iain [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Plot Mixtures of Synthetically Generated Gamma Distributions
Are you trying to look at the difference in the gamma distributions due to variations in the shape and scale parameters? In this case, the following approach might be more straightforward: ## assign parameter values params - list(curve1=c(1,1),curve2=c(1,2),curve3=c(1,3)) ## define function gammafun - function(shape,scale) { p - seq(0.001,0.999,length=1000) x - qgamma(p,shape,scale) y - dgamma(x,shape,scale) list(x=x,y=y) } ## apply function to parameters dat - lapply(params,function(p) gammafun(p[1],p[2])) ## plot lines xlim - range(sapply(dat,`[[`,x)) ylim - range(sapply(dat,`[[`,y)) plot.new() plot.window(xlim,ylim) for( i in 1:3 ) lines(dat[[i]],col=i) lapply(1:2,axis) box() legend(topright,lty=1,col=1:3,legend=names(dat)) - Original Message From: Gundala Viswanath [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Sunday, July 6, 2008 8:24:06 PM Subject: [R] Plot Mixtures of Synthetically Generated Gamma Distributions Hi, I have the following vector which is created from 3 distinct distribution (three components) of gamma: x=c(rgamma(30,shape=.2,scale=14),rgamma(30,shape=12,scale=10),rgamma(30,shape=5,scale=6)) I want to plot the density curve of X, in a way that it shows a distinct 3 curves that represent each component. How can I do that? I tried this but doesn't work: lines(density(x)) Please advise. - Gundala Viswanath Jakarta - Indonesia __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Method for checking automatically which distribtions fits a data
I don't know that there is a single function, but you can perhaps apply a sequence of available functions - For instance, you can use fitdistr() in library(MASS) to estimate optimal parameters for a candidate set of distributions; then look at each fit and also compare the deviance among the fits (possibly penalizing distributions which require more parameters - for instance, using the Akaike Information Criterion(?)). - Original Message From: Gundala Viswanath [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Sunday, July 6, 2008 4:50:20 PM Subject: [R] Method for checking automatically which distribtions fits a data Hi, Suppose I have a vector of data. Is there a method in R to help us automatically suggest which distributions fits to that data (e.g. normal, gamma, multinomial etc) ? - Gundala Viswanath Jakarta - Indonesia __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] operations on all pairs of columns from two matrices
how about this? m1 - matrix(rep(1:3,each=5),ncol=3) m2 - matrix(1:15,ncol=3) array(apply(m1,2,function(x,m) m-x,m2),dim=c(dim(m2),ncol(m1))) - Original Message From: Daren Tan [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Wednesday, June 18, 2008 7:36:45 AM Subject: [R] operations on all pairs of columns from two matrices m1 - matrix(rnorm(40), ncol=4) m2 - matrix(rnorm(40), ncol=4) I would like to subtract first column of m1 from all columns of m2, subtract 2nd of m1 from all columns of m2, and so on. Obviously, I am not using the appropriate function outer(m1, m1, -), since the first column isn't all 0s. _ [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] try catch block
This is a useful reference on the tryCatch() function: http://www1.maths.lth.se/help/R/ExceptionHandlingInR/ I think something like this should work: xml - tryCatch(xmlTreeParse(xmlTxt, useInternal=TRUE), error=function(err) xmlMalFormed()) - Original Message From: ppatel3026 [EMAIL PROTECTED] To: r-help@r-project.org Sent: Tuesday, June 17, 2008 2:15:43 PM Subject: [R] try catch block How can I use the try catch block such that if this statement fails xml - xmlTreeParse(xmlTxt, useInternal=TRUE) then this statement is executed xml - xmlMalFormed() ? This code does not work but assuming its somewhere along these lines: tryCatch(xml - xmlTreeParse(xmlTxt, useInternal=TRUE), xml - xmlMalFormed(f1)) -- View this message in context: http://www.nabble.com/try-catch-block-tp17938467p17938467.html Sent from the R help mailing list archive at Nabble.com. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] adding custom axis to image.plot() and strange clipping behavior
Hi list, I wanted to plot an image with a colorbar to the right of the plot, but set my own axis labels (text rather than numbers) to the image. I have previously accomplished this with two calls to image(), but the package 'fields' has a wrapper function, image.plot(), which does this task conveniently. However, I could not add axes to the original image after a call to image.plot(); I have found that I needed to set par(xpd=TRUE) within the function to allow this to happen: ###=== begin code library(fields) ## make data matrix m - matrix(1:15,ncol=3) ## plot image.plot(m,axes=FALSE) axis(1) # doesn't work par(xpd=TRUE) axis(1) # still doesn't work ## replace the 28th element of the body of image.plot() ## and assign to new function called 'imp' ## here I just use the second condition of 'if' statement ## and set 'xpd = TRUE' imp - `body-`(image.plot,value=`[[-`(body(image.plot),28, quote({par(big.par) par(plt = big.par$plt, xpd = TRUE) par(mfg = mfg.save, new = FALSE) invisible()}))) imp(m,axes=FALSE) box() axis(1,axTicks(1),lab=letters[1:length(axTicks(1))]) ## clip to plotting region for additional ## graphical elements to be added: par(xpd=FALSE) abline(v=0.5) ###=== end code I wonder if anyone has any insights into this behavior? Since in the axis() documentation, it says: Note that xpd is not accepted as clipping is always to the device region I am surprised to find (1) that the par(xpd=TRUE) works in the case above, and (2) that it must be called before the function call is terminated. I wonder if anyone has any insights into this behavior. I have reproduced this on both my Linux box (Ubuntu Gutsy Gibbon 64-bit, R 2.7.0, fields package version 4.1) and Windows machine (32-bit XP Pro, R 2.7.0, fields package version 4.1). Thanks very much, Stephen __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Data manipulation
Hi Klaus, I am not exactly sure what you are asking for, but something like this? This would be option (2) from your list - I don't know that it would be too difficult in R that you would want to use another tool. filt - function(x) with(x,which(Hole 1)) normalize - function(x,y) { x$Feature - x$Feature - with(y,Nominel[match(x$Hole,Hole)]) return(x) } # from CSV import mydata - read.csv(...) # answer normalizedData - normalize(filt(mydata)) --- Klaus Friis Østergaard [EMAIL PROTECTED] wrote: Hi, I have a data set which is like this I write as the CSV I import: Sample;Hole;Feature;Value 1;5;x;4,2334 1;5;y;3,3434 1;5;r;0,1080 1;10;x;5,2526 1;10;y;4,3434 1;10;r;0,1080 with 98 sample and 10 different holes. These are measured values. Now I also have a list of nominel values: Hole;Feature;Nominel;LSL;USL 5;x;4,25,4,20;4,30 5;y;3,35;3,30;3,40 5;r;0,10;0,07;0,13 10;x;5,25;5,20;5,30 ... If I want to normalize the measured values. The results are to be used in a Sweave file that I plan to reuse for several similar data sets in the furture. I have been looking at different approache: 1. do it in a script out side R 2. do it the long and hard way by filtering out all the single holes and Feature, the on this list subtract the nominel values, and then combine it back. 3. ? Any help and guidence apriciated -- Klaus F. Østergaard, farremosen(at)gmail dot com [[alternative HTML version deleted]] __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] vector name
Hi, Either of the following should work (I assume there are 28 elements in your list): fdata - cbind(as.matrix(as.data.frame(filtered)), myregime) fdata - cbind(colnames-(matrix(unlist(filtered),ncol=28), names(filtered)), myregime) --- livia [EMAIL PROTECTED] wrote: I have got a list named filtered, I would like to construct alist named fdata as following: fdata - cbind(matrix(unlist(filtered),ncol=28), myregime) If I try names(filtered), it gives all the correct name for each vector, but if I try names(fdata), it appears filtered[[1]] filtered[[2]] ..., How can I keep the name in fdata? Could anyone give me some advice? -- View this message in context: http://www.nabble.com/vector-name-tf4466025.html#a12733890 Sent from the R help mailing list archive at Nabble.com. __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Luggage? GPS? Comic books? __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.