Re: [R] Legend text populated with calculated values and super script?
Thanks everyone for the help. Dennis, the bquote version work great. Thanks, Doug On 2/7/2014 7:08 PM, Dennis Murphy wrote: Here's a bquote version: x=c(1,2,3,4); y=c(1,2,3,4); z=c(1.25,1.5,2.5,3.5) # first stats based on data, used to populate legend wdt_n = 50; wdt_mbias = 0.58 wdt_mae = 2.1; wdt_R2 = 0.85 # second stats based on data, used to populate legend spas_n = 50; spas_mbias = 0.58 spas_mae = 2.1; spas_R2 = 0.85 wleg <- bquote(paste("WDT (", N == .(wdt_n), ", ", Bias == .(wdt_mbias), ", ", MAE == .(wdt_mae), ", ", R^2 == .(wdt_R2), ")")) sleg <- bquote(paste("SPAS (", N == .(spas_n), ", ", Bias == .(spas_mbias), ", ", MAE == .(spas_mae), ", ", R^2 == .(spas_R2), ")")) plot(x,y, col="red1", pch=1); lines(x,z, type="p", col="green4",pch=3) legend("topleft", legend = as.expression(c(sleg, wleg)), col=c("red1","green4"), pch=c(1,3), cex=0.85) Dennis On Fri, Feb 7, 2014 at 4:58 PM, David Winsemius wrote: On Feb 7, 2014, at 7:54 AM, Douglas M. Hultstrand wrote: Hello, I am trying to generate a plot legend that contains calculated summary statistics, one statistic is R^2. I have tried several variations using the commands "expression" and "bqoute" as stated on the R help pages. I have not been able to get the R^2 super script correct along with the calculated statistics. I provided an example below, what I want is the legend (wdt_leg and spas_leg) as below but with the R^2 as superscript. # Example Data x=c(1,2,3,4); y=c(1,2,3,4); z=c(1.25,1.5,2.5,3.5) # first stats based on data, used to populate legend wdt_n = 50; wdt_mbias = 0.58 wdt_mae = 2.1; wdt_R2 = 0.85 # second stats based on data, used to populate legend spas_n = 50; spas_mbias = 0.58 spas_mae = 2.1; spas_R2 = 0.85 # create legend wdt_leg <- paste("WDT (N = ", wdt_n,", Bias = ",wdt_mbias,", MAE = ",wdt_mae, ", R2 = ", wdt_R2, ")", sep="") spas_leg <- paste("SPAS (N = ", spas_n,", Bias = ",spas_mbias,", MAE = ",spas_mae, ", R2 = ", spas_R2, ")", sep="") # create plot plot(x,y, col="red1", pch=1); lines(x,z, type="p", col="green4",pch=3) leg.txt <- c(spas_leg, wdt_leg) legend("topleft", legend = leg.txt, col=c("red1","green4"), pch=c(1,3), cex=0.85) sublist <- structure(list(wdt_n = 50, wdt_mbias = 0.58, wdt_mae = 2.1, wdt_R2 = 0.85, spas_n = 50, spas_mbias = 0.58, spas_mae = 2.1, spas_R2 = 0.85), .Names = c("wdt_n", "wdt_mbias", "wdt_mae", "wdt_R2", "spas_n", "spas_mbias", "spas_mae", "spas_R2")) legends <-c( substitute( atop(WDT * group("(", list(N == wdt_n, Bias == wdt_mbias, MAE == wdt_mae ), ")" ), R^2 == wdt_R2 ) , env=sublist), substitute( atop(SPAS * group("(", list(N == spas_n, Bias == spas_mbias, MAE == spas_mae ), ")"), R^2 == spas_R2 ), env=sublist) ) # I tried with: as.expression( lapply( exprlist, function(e) bquote(e) ) ) but failed repeatedly. # In order to get `substitute` to cook the bacon, you need to use real expressions, not text. plot(x,y, col="red1", pch=1); lines(x,z, type="p", col="green4",pch=3) legend("topleft", legend = as.expression(legends), col=c("red1","green4"), pch=c(1,3), cex=0.85) -- David Winsemius Alameda, CA, USA __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 720.771.5840 email: dmhul...@metstat.com web: http://www.metstat.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] Legend text populated with calculated values and super script?
Hello, I am trying to generate a plot legend that contains calculated summary statistics, one statistic is R^2. I have tried several variations using the commands "expression" and "bqoute" as stated on the R help pages. I have not been able to get the R^2 super script correct along with the calculated statistics. I provided an example below, what I want is the legend (wdt_leg and spas_leg) as below but with the R^2 as superscript. # Example Data x=c(1,2,3,4); y=c(1,2,3,4); z=c(1.25,1.5,2.5,3.5) # first stats based on data, used to populate legend wdt_n = 50; wdt_mbias = 0.58 wdt_mae = 2.1; wdt_R2 = 0.85 # second stats based on data, used to populate legend spas_n = 50; spas_mbias = 0.58 spas_mae = 2.1; spas_R2 = 0.85 # create legend wdt_leg <- paste("WDT (N = ", wdt_n,", Bias = ",wdt_mbias,", MAE = ",wdt_mae, ", R2 = ", wdt_R2, ")", sep="") spas_leg <- paste("SPAS (N = ", spas_n,", Bias = ",spas_mbias,", MAE = ",spas_mae, ", R2 = ", spas_R2, ")", sep="") # create plot plot(x,y, col="red1", pch=1); lines(x,z, type="p", col="green4",pch=3) leg.txt <- c(spas_leg, wdt_leg) legend("topleft", legend = leg.txt, col=c("red1","green4"), pch=c(1,3), cex=0.85) Any help/suggestions on this would be great. Thanks for your time in advance. Doug -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist email: dmhul...@metstat.com web: http://www.metstat.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] Netcdf and Raster Package Questions, Need .asc File for GIS
Hello R-Group, I am new working with netcdf files and the raster package in R.I am trying to read in a netcdf file using the package "ncdf".I am able to get the lat, lon and parameter I need and can plot using fill.contour.Ultimately, I am trying to create a .asc file to reafd into GIS.I am using the package "raster" to read the parameter.When I read in with "raster", the extent of the raster is between 0 and 1 for both x and y directions.Also, I have to transpose the grid so it is oriented the correctly.In order to create the .asc file I have to resample to square grids for "writeRaster" to work. Below I supplied my objective, questions and R code used.(I also attached .docx file with code and images for reference) *_Objective_***- read netcdf file and create .asc file to read into GIS *_Questions:_* 1) using the raster package how can I set the projection, extent, and cell size properly.Here are the dimensions and global attributes of the netcdf file, I used "ncdump -h " dimensions: lon = 4200 ; lat = 2400 ; time = UNLIMITED ; // (1 currently) rainf_profiles = 1 ; tair_profiles = 1 ; global attributes: :missing_value = -.f ; :TITLE = "LIS land surface model output" ; :MAP_PROJECTION = "EQUIDISTANT CYLINDRICAL" ; :SOUTH_WEST_CORNER_LAT = 48.005f ; :SOUTH_WEST_CORNER_LON = -167.995f ; :DX = 0.01f ; :DY = 0.01f ; 2) Is there a better way to read a netcdf file and create an .asc file that can be read into GIS (GRASS or ArcGIS) *_Code Used_* # get net cdf file, big file wget ftp://ftp.nohrsc.nws.gov/pub/staff/fall/Hultstrand/NOAH32.20120411.d01.nc ## COMMANDS ## ## # look at netcdf file header info ncdump -h NOAH32.20120411.d01.nc ## # Start R # ## library(ncdf) ex.nc = open.ncdf("NOAH32.20120411.d01.nc") print(ex.nc) summary(ex.nc) x = get.var.ncdf(ex.nc, "lon") y = get.var.ncdf(ex.nc, "lat") swe = get.var.ncdf(ex.nc, "SWE") # kg/m2 swe_in <- swe * 0.0393701 # image plot of swe, takes time to load filled.contour(x,y,swe_in, color = terrain.colors, asp = 1) # load raster library library(raster) r = raster(swe_in) # raster is sideways, rotate m <- t(swe_in) m <- m[nrow(m):1,] r <- raster(m) plot(r) writeRaster(r,file="test_grid2.asc", format="ascii") # need square grids # resample to square grids r2 = raster(r) res(r2) = min(res(r)) res(r2) r2 <- resample(r, r2, method='bilinear') writeRaster(r2,file="test_grid24.asc", format="ascii") Thanks, Doug -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 720.771.5840 email: dmhul...@metstat.com web: http://www.metstat.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] data frame row statistics (mean)?
Hello, I am trying to calculate the mean value of each row in a data frame (d), I am having troubles and getting errors using the code I have written. Below is a brief example of the code, any thought or suggestions would be great. Thank you for your time, Doug # Example Code: d <- data.frame(st1=c(1,2,3,4), st2=c(2,5,6,7), st3=c(5,5,NA,7), st4=c(6,5,7,8)) avg <- rep(NA,length(d[,1])) for (i in 1:length(d[,1])) { avg[i] = mean(d[i,1:4], na.rm=TRUE) } # Final Output wanted. st1 st2 st3 st4 avg 1 1 2 5 6 3.50 2 2 5 5 5 4.25 3 3 6 NA 7 5.33 4 4 7 7 8 6.50 -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 720.771.5840 email: dmhul...@metstat.com web: http://www.metstat.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] Unique Data Frame Name?
Hello, I am trying to create a data frame with a unique name, based on indexing of for loop. I was wondering if there is a way to do this, I keep running into errors when I try to do this. Below is a brief example, I am trying to get two data frames (name1 and name2). Any suggestions are appreciated. Thanks, Doug # Example for (i in 1:2) { x=c(1,2,3,4) y=c(10,20,30,40) G <- paste("name", i, sep="") G[i] <- data.frame(x,y) } -- --------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 720.771.5840 email: dmhul...@metstat.com web: http://www.metstat.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] Times series data file?
Hello, I currently splitting a file into individual files (time series each separated into one file), the file I read in skips the first four lines and extracts the data columns I need. I was wondering if there is a way for R to automatically scan and separate the files based on the head information? The header delineates the observation with a 254 space time space day space month space year. 254 0 26 NOV1995 I would like to then use the program I have written to do the analysis. I have attached a small subset text file of data (two observations). Any thoughts would be very helpful. # Read in data file data <- read.table("file.txt", skip=4, header=F) temp <- data$V4 elev <- data$V3 Thank you, Doug -- ------------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 720.771.5840 email: dmhul...@metstat.com web: http://www.metstat.com - 254 0 26 NOV1995 1 24232 72694 44.92N123.02W61 2302 2100 1960 2680149 9 4 3 SLE9 kt 9 10071 61106 94180 10 5 10037 89110 82183 12 4 1120106 84186 12 6 9780304 9 9205 19 6 9500544 74 59221 19 254 12 26 NOV1995 1 24232 72694 44.92N123.02W61 2302 2100 1960 2680149 9 4 3 SLE9 kt 9 10071 61106 94180 10 5 10037 89110 82183 12 4 1120106 84186 12 6 9780304 9 9205 19 6 9500544 74 59221 19 __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/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] Legend symbol?
Hello, I am creating a plot/image using different data and a couple fit lines (see attached image). In the legend, I want the Default and Exponential symbol to be a line. I am using the pch command, I tried to use "-" to represent a line but does not work so I currently have set as a "1". Any thoughts or suggestions would be greatly appreciated. Below are the commands I used to create the legend: if(Prehour == 1) { leg.txt <- c("Data", "Statistical Outlier", "Spatial Outlier", "High Z Outlier", "Default","Exponential (used)") } else { leg.txt <- c("Data", "Statistical Outlier", "Spatial Outlier", "High Z Outlier", "Default (used)","Exponential") } legend("topleft", legend=leg.txt, col=c("black","yellow","red","orange","blue","black"), pch = c(16,16,16,16,1,1), cex=0.85 ) Thanks, Doug -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Plot frame border to start at zero?
Hello, I am creating plots of hourly precipitation and accumulated precipitation (on different axis, see attached image). I was wondering how can I have the plot frame (black border) start at zero, it looks like it is plotted less than zero? The code I use to create the png files is below: CairoPNG(PNG_file,width=1000, height=600, pointsize=14, bg="white") opar <- par(mai = c(.8, .8, 1, .8))# Set margins plot(ppt,type="h",col="dark grey",ylim=c(0,max_ppt+1), lwd=6, xlab='', ylab='', main=title, frame.plot=T, axes=F) axis(2, col="black", las=2) par(new=T) # R to overwrite the first plot plot(accum, type="l", col="blue", axes=F, ylab='', xlab='', lwd=2) axis(1, col="black", las=1) axis(4, pretty(c(0, max_accum) ), col="black", las=2) legend("topleft", legend=c('Incremental', 'Accumulated'), col=c("dark grey", "blue"), lwd=c(6, 2.0)) legend((length(n)-4),max_accum, legend=paste(round(max_accum,2)), bty="n", cex=.90) ### max accum location mtext(paste("Lat:", .lat, "Lon:", .lon), cex=0.95) mtext("Index Hour", side=1, line=2) mtext("Incremental Precipitation (in)", side=2, line=2.5) mtext("Accumulated Precipitation (in)", side=4, line=2) dev.off() Thanks for all your help, Doug - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.com - <>__ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] R matching lat/lon pairs from two datasets?
Hello, I am trying to match lat/lon from one dataset with the lat/lon from a second dataset and use that rows data for calculations. I am using match, but this is finding the first match and not comparing the pair, how can I determine if the lat/lon are the same? See example below. Is there a better way to determine to a matching pair of lat/lon values? Example Datasets: > data2 V1V2 V3 1 -123.76 47.82 8 2 -123.75 47.82 11 > data[1:2] V1 V2 1 47.82 -123.76 2 47.82 -123.75 3 47.82 -123.74 4 47.82 -123.73 #Subset of current R code : lat <- data$V1 lon <- data$V2 yrs <- c(1,2,5,10,25,50,100,200,500,1000) lon2 <- data2$V1 lat2 <- data2$V2 ppt2 <- data2$V3 for(i in 1:length(lat2)) { loc <- match(lat2[i],lat) loc2 <- match(lon2[i], lon) print(loc); print(loc2) #Need to test to make sure loc equals loc2 freq_ppt <- c(data[i,4],data[i,6],data[i,8],data[i,10],data[i,12],data[i,14],data[i,16],data[i,18],data[i,20],data[i,22]) print(freq_ppt) return_value <- approx(freq_ppt,yrs,xout=data2[i,3]) print(return_value) } Thanks for your help, Doug -- --------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] paste name in for loop?
Hello, I am trying to create subsets of grouped data (by area size), and use the area size as part of the output name. The code below works for area (xout) 1 and 50, the other files are given NA for an area. A simple example: xout <- c(1,5,10,25,50,100) for(i in xout) { print(paste("Areal_Ppt_",xout[i],"sqmi.txt", sep="")) } [1] "Areal_Ppt_1sqmi.txt" [1] "Areal_Ppt_50sqmi.txt" [1] "Areal_Ppt_NAsqmi.txt" [1] "Areal_Ppt_NAsqmi.txt" [1] "Areal_Ppt_NAsqmi.txt" [1] "Areal_Ppt_NAsqmi.txt" The actual code and partial dataset are below. Thanks for your help, Doug ### ### Real Code ### ### data2 <- read.table("GROUP.txt", header=T, sep=",") xout <- c(1,5,10,25,50,100) for(i in xout) { name <- paste("Areal_Ppt_",xout[i],"sqmi.txt", sep="") b.1 <- subset(data2, area == i) write.table(b.1, file=name,quote=FALSE,row.names=FALSE, sep=",") } ## ### Dataset GROUP.txt ### ### hr,area,avg_ppt 21,1,0 21,5,0.001 21,10,0.001 21,25,0.005 21,50,0.01 21,100,0.011 22,1,0.003 22,5,0.005 22,10,0.00824 22,25,0.04258 22,50,0.057 22,100,0.101 23,1,2.10328 23,5,2.02755 23,10,1.93808 23,25,1.78408 23,50,1.67407 23,100,1.568 24,1,3.20842 24,5,3.09228 24,10,2.95452 24,25,2.71661 24,50,2.54607 24,100,2.38108 -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] lmomco package and confidence limits?
Hello, I am using the lmomco package (lmom.ub and pargev) to compute the GEV parameters (location, scale, and shape), which are used to estimate return values. I was wondering how/if I can calculate upper and lower confidence (CI_u, CI_l) intervals for each return frequency using the GEV parameters to fill-in the table below? Xi (location) = 35.396 Alpha (scale) = 1.726 Kappa (shape) = 0.397 Year, Return value, CI_u, CL_l 2, 36.0, 5, 37.3, 10, 38.0, 25, 38.5, 50, 38.8, 100, 39.0, Thank you for your help/suggestions, Doug -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] data frame subsets?
Hello, I am trying to create data frame subsets based on binned temperature data. I have code working to create the bins (d.1 and d.2), but it takes two steps, I was wondering if I could merge into one step. See Below d n year mo da hr t td tw rh kPa 1 1 1945 3 1 0 1.1 0.0 0.6 92 101.7 2 2 1945 3 1 1 2.8 -1.1 1.1 76 101.8 3 3 1945 3 1 2 2.2 -1.7 0.6 75 101.9 4 4 1945 3 1 3 1.7 -1.1 0.6 82 102.0 5 5 1945 3 1 4 1.7 -2.8 0.0 72 102.1 6 6 1945 3 1 5 1.7 -1.7 0.0 78 102.2 7 7 1945 3 1 6 1.1 -2.8 0.0 75 102.2 8 8 1945 3 1 7 1.1 -1.7 0.0 82 102.4 9 9 1945 3 1 8 1.7 -1.1 0.6 82 102.5 10 10 1945 3 1 9 2.8 -3.3 0.6 64 102.6 d.1 <- d[d$t >= 1.0,] d.2 <- d.1[d.1$t < 2.0,] How can I make d.1 and d.2 into one step? I have tried several different methods such as example below. d.1 <- d[d$t >= 1.0, && d$t < 2.0,] Thanks, Doug -- ------------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] New vector based on if/else statement within for loop?
Hello, I am trying to create a new vector (w) that is based on comparing two vectors (P and Z). The compaison is simple (I created a for loop that reassigns w based on if statement), all Z values >= 24 and P values <=1, w=88 else w=77. I am not getting the correct results for w, see example code below. Any thoughts or suggestions on the correct method. Thank you, Doug P <- c(0,1,2,3,4,5,0,1,5) Z <- c(25,23,28,29,30,31,28,29,22) w <- P for (i in length(w)) { if(Z[i]>=24 && P[i]<=1) { w[i] = 88 } else { w[i] = 77} } d.f <- data.frame(Z,P,w) d.f Z P w 1 25 0 0 2 23 1 1 3 28 2 2 4 29 3 3 5 30 4 4 6 31 5 5 7 28 0 0 8 29 1 1 9 22 5 77 -- ------------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Cairo package, png files within for loop are black?
Hello, I am generating .png images using the Cairo package in a for loop (looping on the number of zones, number of zones equals the number of plots to create based on different zone data). When I run the R script the .png files are created but they are all black? If I comment out the for loop and force my zones to equal one the png file is created correctly? Is there an issue with generating .png files within a for loop? Create .png commands within for loop: CairoPNG(paste(t.g), width=800, height=600, pointsize=12, bg="white") xyplot(areasqmi ~ value, x.p, groups=dur, main=(t.n), ylab=expression("Area(mi" ^ 2 * ")"), xlab="Maximum Average Depth of Percipitation (inches)", scales=list(y=list(log=TRUE)), ylim=c(1,100), type='l', auto.key=list(space='right')) dev.off() -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Singular Gradient Test
Hello, I posted this question last week and have not heard anything, I am wondering if anyone had ideas for testing a model relationship? I am working with a real-time hydrologic modeling system, and I am using R (R batch script on Linux) to create a non-linear relationship (exponential) between observed data. I want to extract the non-linear coefficients (“b” and “m”) if the relationship can be created, if the relationship cannot be created I will use default “b” and “m” coefficients. In the R script I some times get an error of singular gradient matrix (see below). I want to test whether I can create the relationship (singular gradient causes the script crash) and use the model extracted coefficients or use default coefficients. Model in R batch script: fit.nls <- nls(P~(b*exp(m*Z)), start=list(m=0.015,b=0.017), control=list(maxiter=200)) Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at initial parameter estimates ** the initial parameter values are also the default Specific Questions: 1) Is there a way to test fit.nls (or the data) prior to see if this error occurs. 2) Would this test be set up as an if statement? if (fit is good) {proceed model coefficients} else {use default coefficients}? Thanks for all your help, Doug -- ----- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Data frame search and remove questions
Hello, I have a couple questions about removing rows from a data frame and creating a new data frame with the removed values. I provided an example data frame (d) below. Questions: 1) How can I search for "-999.000" and remove the entire row from data frame "d"? (all -999 values will be in sd_diff) 2) Can I create a new data frame "d.new" that only contains the removed rows? 3) How can I remove the last two rows from a data frame. (I used append command to add two values to the end of the data) > d lat.add lon.add PPT.add Z.add sd_dif 137.67 -95.48 1.000 368 1.017 238.82 -92.22 13.208 383 5.737 337.30 -95.50 6.096 130 4.377 437.08 -95.57 0.508 106 -999.000 538.73 -93.55 6.350 370 6.233 638.83 -94.88 0.254 5 8.607 738.33 -96.18 0.50843 8.665 838.85 -94.73 1.000 5 -999.000 938.71 -93.16 1.016 320 3.717 10 38.95 -95.67 1.000 5 8.553 > d.new lat.add lon.add PPT.add Z.add sd_dif 137.08 -95.57 0.508 106 -999.000 238.85 -94.73 1.000 5 -999.000 Thanks for all the help, Doug -- --------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Plot nls line on plot?
Hello, I have a non-linear function (exponential) that I am trying to display the line with the data in a plot, is there a command similar to abline() for the function I created, if not what is the best way to display the fitted line. Example code below. ### Example z <- c(1,10,15,20,25,30,35,40,45,50,55,60) p <- c(.02,.08,.2,.45,1.03,2.36,5.37,12.24,27.85,63.39,144.27,328.35) cnt <- length(z) fit <- nls(p~(b*exp(m*z)), start=list(m=.1645,b=.017), control=list(maxiter=200)) plot(p~z) # want to add fit/line to plot Thanks, Doug -- --------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Linear Model "NA" Value Test
Hello, I am deriving near real-time liner relationships based on 5-min precipitation data, sometimes the non-qced data result in a slope of NA. I am trying to read the coefficient (in this example x) to see if it is equal to NA, if it is equal to NA assign it a value of 1. I am having trouble with the if statement not recognizing the coefficient or "NA" value in the test. Any thoughts, I supplied a really basic example below. Thank you, Doug # ## Example ## # x=c(1,1,1) y=c(1,1,1) fit <- lm(y~x) fit Call: lm(formula = y ~ x) Coefficients: (Intercept)x 1 NA coef <- coef(fit) fit$coef[[2]] [1] NA if("fit$coef[[2]]" == "NA") {.cw = 1} -- --------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Read multiple files into dataframe?
Hello, I am fairly new to R programming and am stuck with the following problem. I am trying to read in multiple files (see attached file or at end of email), the files all have the same general header information and different precipitation (avgppt) and area (areasqmi) values. Some times the number of records are different in the files. I want to read in all files (.stdsummary), and create a dataframe that contains the area and precipitation for each file (files are different duration), and supply a header name that represents the duration (sixth line down in header information or extracted from data file "da_zone1_15hr_1166.stdsummary"). For example, this is what the final dataframe would look like for 1hr, 3hr, and 15hr datafiles: 1hrppt 1hrarea3hrppt 3hrarea15hrppt 15hrarea 3.806.8607.670 3.7116.7817.61 3.6956.7257.525 3.56106.55107.3210 3.33206.17206.9120 2.87505.25505.950 2.451004.351005.02100 1.942003.342004.09200 1.673002.783003.55300 The end result is to perform QC statistics and then plot each set of data. Also, is there away to create a dataframe that has different # of records? Datafile example of file below: Storm number: 1166 Zone number: 1 (ALL zones) Number of stations: 172 Total analyzed area (sq mi): 5360.8 Average station density (stns per 1000 sq mi): na Duration window (hours): 15 CPP beg hour index: 1 CPP end hour index: 15 Ishohyet interval step (inches): 0.2 Standard area size summary Begin run date/time: Tue Aug 25 01:17:43 2009 avgppt, areasqmi 7.67,000.00 7.60,001.00 7.52,005.00 7.32,010.00 6.91,020.00 5.90,050.00 5.02,100.00 4.09,200.00 3.55,300.00 2.96,500.00 2.27,0001000.00 1.64,0002000.00 0.82,0005000.00 0.77,0005360.00 -- ----- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.com - Storm number: 1166 Zone number: 1 (ALL zones) Number of stations: 172 Total analyzed area (sq mi): 5360.8 Average station density (stns per 1000 sq mi): na Duration window (hours): 15 CPP beg hour index: 1 CPP end hour index: 15 Ishohyet interval step (inches): 0.2 Standard area size summary Begin run date/time: Tue Aug 25 01:17:43 2009 avgppt, areasqmi 7.67,000.00 7.60,001.00 7.52,005.00 7.32,010.00 6.91,020.00 5.90,050.00 5.02,100.00 4.09,200.00 3.55,300.00 2.96,500.00 2.27,0001000.00 1.64,0002000.00 0.82,0005000.00 0.77,0005360.00 __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] Cairo Package Installation
I am trying to install the Cairo package on a linux machine, the Cairo package did not install correctly (could not find cairo.h), I am new to R and linux any help on the installation would be great. Below are output from trying to install the Cairo package, thought this might help. > install.packages("Cairo") Warning in install.packages("Cairo") : argument 'lib' is missing: using '/home/tyep/R/x86_64-unknown-linux-gnu-library/2.8' trying URL 'http://streaming.stat.iastate.edu/CRAN/src/contrib/Cairo_1.4-4.tar.gz' Content type 'application/x-gzip' length 75200 bytes (73 Kb) opened URL == downloaded 73 Kb * Installing *source* package 'Cairo' ... checking for gcc... gcc -std=gnu99 checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc -std=gnu99 accepts -g... yes checking for gcc -std=gnu99 option to accept ISO C89... none needed checking how to run the C preprocessor... gcc -std=gnu99 -E checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for ANSI C header files... yes checking for sys/wait.h that is POSIX.1 compatible... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking for string.h... (cached) yes checking sys/time.h usability... yes checking sys/time.h presence... yes checking for sys/time.h... yes checking for unistd.h... (cached) yes checking for an ANSI C-conforming const... yes checking for pkg-config... /usr/bin/pkg-config checking whether pkg-config knows about cairo... no configure: CAIRO_LIBS is unset, attempting to guess it. configure: CAIRO_CFLAGS= checking if R was compiled with the RConn patch... no checking cairo.h usability... no checking cairo.h presence... no checking for cairo.h... no configure: error: Cannot find cairo.h! Please install cairo (http://www.cairographics.org/) and/or set CAIRO_CFLAGS/LIBS correspondingly. ERROR: configuration failed for package 'Cairo' ** Removing '/home/tyep/R/x86_64-unknown-linux-gnu-library/2.8/Cairo' The downloaded packages are in /tmp/RtmpILmmXw/downloaded_packages Warning message: In install.packages("Cairo") : installation of package 'Cairo' had non-zero exit status > Thanks, Doug -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.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] Display Equation on plot
Hello, I am using the lm to fit a linear model to data, I was wondering if there is a way to display the equation on a plot using the extracted lm coefficients? I am using the plot() function to create the plot/.png. Example: lm_mod <- lm(data1~data2) intercept = 48.54 slope = 0.4856 I want to display equation on a plot as y=0.4856x+48.54 Any thoughts or suggestions are appreciated. Thanks, Doug -- ----- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhul...@metstat.com web: http://www.metstat.com __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Re: [R] Save a function existing library
Thanks everyone, Jorge I used your suggestion and this works perfect. Doug Jorge Ivan Velez wrote: Dear Douglas, I'm not quite sure about that, but you could do something like: 1. Save for function in txt format 2. Use source() to load it into R As a toy example, suppose you have function called "myfunction" which is defined as: myfunction=funciton(x,y) x^y Now, suppose you save "myfunction" in a text file in "C:/temp/functions", with the same name ("myfunction.txt"). To load and use "myfunction" in R, you type: source("C:/temp/functions/myfunction.txt") myfunction(2,3) which result, of course, would be 8. Another option is to save your function in the file "..\etc\Rprofile.site" as Xiaoxu LI suggested before. HTH, Jorge On Thu, Oct 30, 2008 at 1:45 PM, Douglas M. Hultstrand <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>> wrote: Hello all, I am fairly new to R and I have created a function that I use quit frequently. I was wondering if there is away to save this function in an existing library so I can call it by using the function name once the library is loaded? Thanks, Doug -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: [EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> web: http://www.metstat.com __ R-help@r-project.org <mailto:R-help@r-project.org> mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: [EMAIL PROTECTED] web: http://www.metstat.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] Save a function existing library
Hello all, I am fairly new to R and I have created a function that I use quit frequently. I was wondering if there is away to save this function in an existing library so I can call it by using the function name once the library is loaded? Thanks, Doug -- - Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: [EMAIL PROTECTED] web: http://www.metstat.com __ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[R] R for loop question
Hello, I am trying to assign a variable name (x1,x2,x3...) in a loop statement that is based on a counter (counter is based on the number of hours within the datafile). The x1,x2 data will later be called for plotting the data. Below is a clip of the for loop I am using, any suggestions? k = 1 for (i in 1:length(stats$hour)) { "x(i)" = dataset[k,(3:15)] k = k+1 } Thanks, Doug -- ----- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: [EMAIL PROTECTED] web: http://www.metstat.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.