xhn r resumen

Upload: carlos-blanco

Post on 05-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Xhn R Resumen

    1/39

    R

    Iniciar R:Consola->md c:\trabajo->cd c:\trabajo- >R o bien SAVE->ruta y fichero destino

    Salir: q()Ayuda: help() o help.start();

    Funciona el TAB para autocompletado.

    Instalar paquetes:chooseCRANmirror( "" ) Spain(MADRID)=>59install.packages(pkgs, lib, repos = getOption("repos"),

    contriburl = contrib.url(repos, type),method, available = NULL, destdir = NULL,

    dependencies = NA, type = getOption("pkgType"),configure.args = getOption("configure.args"),configure.vars = getOption("configure.vars"),clean = FALSE, Ncpus = getOption("Ncpus", 1L),libs_only = FALSE, INSTALL_opts, ...)

    VIP) install.packages("tree"); install.packages("e1071"); install.packages("datasets");install.packages("class"); install.packages("igraph"); install.packages("MVA");install.packages("MASS"); install.packages("arules"); install.packages("boost");install.packages("stats"); install.packages("caTools"); install.packages("Matrix");install.packages("lattice");

    install.packages(c("pkg1", "pkg2"))install.packages("Rcmdr", dependencies = TRUE)O TB win: Men paquetes->instalar paquetes->marcar y OKdownloaded 106 Kb. package tree successfully unpacked and MD5 sums checkedPaquetes importantes y ayuda de los mismos:

    help("tree") ==> rboles de clsificacin o regresin.help("datasets") ==> hojas de datos ejerccios. data(iris); ls(); iris[1:5,]

    Package : e1071 include svm, naiveBayes , .> install.packages("e1071")

    Packages for Machine learning:For classification: tree in tree, svm in e1071, knn in class,

    lda in MASS, adaboost in boostFor clustering: kmean in stats

    Other useful packages: caTools kernlab mlbench cluster

    RECUERDA CARGAR LOS PAQUETES QUE VAYAS A UTILIZARSe puede hacer desde cdigo con: library(nombrepaquete); ==>library("e1071");

    demo("graphics") Ejemplo de rutinas de dibujo del sistema.?plot() ayuda del comando plot

    http://c/trabajo-http://c/trabajo-
  • 7/31/2019 Xhn R Resumen

    2/39

    Las #ordenes se separan mediante punto y coma, (`;'), o mediante un cambio de l##nea.Si al terminar la l##nea, la orden no est#a sint#acticamente completa, R mostrar#a un signo decontinuaci#on, por ejemplo +

    Ejecuci#on de #ordenes desde un archivo y redirecci#on de la salida: source("#ordenes.R")

    sink("resultado.lis")enviar#a el resto de la salida, en vez de a la pantalla, al archivo del sistema operativo,resultado.lis, dentro del directorio de trabajo. La orden> sink()devuelve la salida de nuevo a la pantalla.Si utiliza nombres absolutos de archivo en vez de nombres relativos, los resultados sealmacena#an en ellos, independientemente del directorio de trabajo.

    objects()se puede utilizar para obtener los nombres de los objetos almacenados en R. Esta funci#ones equivalente a la funci#on ls().

    Para eliminar objetos puede utilizar la orden rm, por ejemplo:> rm(x, y, z, tinta, chatarra, temporal, barra)Para mostar un objeto vale con ejecutar su nombre. Ej: > x 3; x ==> [1] 3 (vector de 1 el)

    Los objetos creados durante una sesi#on de R pueden almacenarse en un archivo para suso posterior. Al analizar la sesi#on, R pregunta si desea hacerlo. En caso afirmativo todos objetos sealmacenan en el archivo `.RData' en el directorio de trabajo.Es recomendable que utilice un directorio de trabajo diferente para cada problema queanalice con R. Es muy com#un crear objetos con los nombres x e y, por ejemplo.

    La estructura m#as simple es el vector, que esuna colecci#on ordenada de n#umeros. Para crear un vector, por ejemplo x, consistente encinco n#umeros, por ejemplo 10.4, 5.6, 3.1, 6.4 y 21.7, use la orden

    > x x

    Si una expresi#on se utiliza como una orden por s## misma, su valor se imprime y se pierde3.As## pues, la orden> 1/xsimplemente imprime los inversos de los cinco valores anteriores en la pantalla (por supuesto,el valor de x no se modica).

    Si a continuaci#on hace la asignaci#on> y

  • 7/31/2019 Xhn R Resumen

    3/39

    v = (mayor o igual),== (igual), y != (distinto). Adem#as, si c1 y c2 son expresiones l#ogicas, entonces c1&c2 es

    su intersecci#on (\conjunci#on"), c1|c2 es su uni#on (\disyunci#on") y !c1 es la negaci#on de c1

    Cadenas: a [1] "HOLA"

  • 7/31/2019 Xhn R Resumen

    4/39

    la funci#on paste() une todos los vectores de caracteres que se le suministran y construye una solacadena de caracteres: > labs fruta names(fruta) postre

  • 7/31/2019 Xhn R Resumen

    5/39

    Getting Started with RSee also the introduction to R here . There's also an Rwiki(http://rwiki.sciviews.org/doku.php ) with lots of useful information, tips etc.

    The online help pages can be accessed as follows:help.start() # Load HTML help pages into browserhelp(package) # List help page for "package"?package # Shortform for "help(package)"help.search("keyword") # Search help pages for "keyword"?help # For more optionshelp(package=base) # List tasks in package "base"q() # Quit R

    Some extra packages are not loaded by default, but can be loaded as follows:library("package")library() # List available packages to loaddetach("package:pkg") # Unload the loaded package "pkg"library(help="package") # list package contents

    Commands can be separated by a semicolon ( ; ) or a newline All characters after # are treated as comments (even on the same line as commands) Variables are assigned using

  • 7/31/2019 Xhn R Resumen

    6/39

    A great feature of R functions is that they offer a lot of control to the user, but provide sensiblehidden defaults. A good example is the histogram function, which works very well withoutany explicit control:

    First, generate a set of 10,000 Gaussian distributed random numbers:data inp inp # Print contents of inp> inp[0] # Print the type of object that inp is:NULL data frame with 5 rows

    > colnames(inp) # Print the column names for inp:[1] "r" "x" "y" # This is simply a vector that can easily bechanged:> colnames(inp) colnames(inp)[1] "radius" "temperature" "time"

    Note that you can refer to R objects, names etc. using the first few letters of the full name, provided that is unambiguous, e.g.:> inp$r # Print the Radius column

    but note what happens if the information is ambiguous or if the column doesn't exist:> inp$t # Could match "inp$temperature" or "inp$time"NULL> inp$wibble # "wibble" column doesn't existNULL

    Alternatively, you can refer to the columns by number:> inp[[1]] # Print data as a vector (use "[[" & "]]")[1] 1 2 3 4 5> inp[1] # Print data as a data.frame (only use "[" and "]")

    Writing data out to a file (if no filename is specified (the default), the output is written to the

    http://www.sr.bham.ac.uk/~ajrs/R/r-access_data.html#data_input_outputhttp://www.sr.bham.ac.uk/~ajrs/R/r-access_data.html#data_input_output
  • 7/31/2019 Xhn R Resumen

    7/39

    console)> write.table(inp, quote=F, row.names=F, col.names=T)radius temperature time1 4.2 14.22 2.4 64.83 8.76 63.44 5.9 32.25 3.4 89.6

    By default the columns are separated by whitespace, but you can change this with the sep=option (see ?write.table for details), e.g. use a : with a tab either side:

    > write.table(inp, quote=F, row.names=F, col.names=T, sep="\t:\t")radius : temperature : time1 : 4.2 : 14.22 : 2.4 : 64.83 : 8.76 : 63.44 : 5.9 : 32.25 : 3.4 : 89.6

    Other types of connection?connections # Help page on opening/closing connectionswrite.table() # Write data to file# You can also refer to URLs for files, e.g.a

  • 7/31/2019 Xhn R Resumen

    8/39

    Plotting dataSee also here

    Useful functions:?plot # Help page for plot command

    ?par # Help page for graphics parameter control?Devices # or "?device"# (R can output in postscript, PDF, bitmap, PNG, JPEG and more formats)dev.list() # list graphics devicescolours() # or "colors()" List all available colours?plotmath # Help page for writing maths expressions in R

    Tip: to generate png, jpeg etc. files, I find it's best to create pdf versions in R, then convertthem in gimp (having specified strong antialiasing, if asked, when loading the pdf file intogimp), otherwise the figures are "blocky" (i.e. suffer from aliasing).

    To create an output file copy of a plot for printing or including in a document etc.

    dev.copy2pdf(file="myplot.pdf") # } Copy contents of current graphicsdevicedev.copy2eps(file="myplot.eps") # } to a PDF or Postscript filedev.copy()

    Adding more datasets to a plot:x

  • 7/31/2019 Xhn R Resumen

    9/39

    Plot chi-squared probability vs. reduced chi-squared for 10 and then 100 degrees of freedomdof

  • 7/31/2019 Xhn R Resumen

    10/39

    replicate(5, sd(rnorm(100)))

    and then compute the mean of the N=5 values:mean(replicate(5, sd(rnorm(100))))

    Obviously 5 is rather small for a number of MC sims (repeat the above command & see how

    the answer fluctuates). Let's try 10,000 instead:mean(replicate(1e4, sd(rnorm(100))))

    With a sample size of 100, the measured sd closely matches the actual value used to create therandom data (sd=1). However, see what happens when the sample size decreases:mean(replicate(1e4, sd(rnorm(10)))) # almost a 3% bias lowmean(replicate(1e4, sd(rnorm(3)))) # >10% bias low

    You can see the bias more clearly with a histogram or density plot:a 30% bias low

    However, in the presence of outliers, mad() is robust compared to sd() as seen with thefollowing demonstration. First, create a function to add a 5 sigma outlier to a Gaussian randomdistribution:outlier

  • 7/31/2019 Xhn R Resumen

    11/39

    ks.test(x, y)

    Correlation testsLoad in some data (see section on data frames , below):dfile

  • 7/31/2019 Xhn R Resumen

    12/39

    Specify 4 plots on same page, in 2x2 configuration:layout(matrix(1:4, nrow=2, ncol=2))layout.show(4) # Show plot layout for 4 plotsplot(m) # Shows useful diagnostics of the fit (4 plots)

    Plot data & best-fit model:

    plot(Tx ~ z, A)abline(m, col="blue") # add best-fit straight line model

    Plot residuals:plot(A$z, resid(m))

    Something fancier: show data, model & residuals in 2 panels:layout(matrix(c(1,1,2)),heights=c(1,1)) # Specify layout for panelslayout.show(2) # Show plot layout for 2 plotsplot(Tx ~ z, data=A)abline(m, col="blue")plot(A$z, resid(m), main="Residuals", col="blue", pch=20)

    Nonlinear least-squares estimates of the parameters of a nonlinear model:?nls

    Since R was developed with experimental (rather than observational) sciences in mind, it isnot geared up to handle errors in both X and Y directions. Therefore the existing algorithms all

    perform regression in one direction only. However, unweighed orthogonal regression isequivalent to principal components analysis.

    Data FramesSee also here

    Create a data frame:A

  • 7/31/2019 Xhn R Resumen

    13/39

    To retrieve a named column, where the column name is itself a variable:name

  • 7/31/2019 Xhn R Resumen

    14/39

    transform(A, c=a^2 + 2*b) # Add new column to data frame

    Similarly, the subset function works in the same way to enable easy filtering of data frames:subset(A, b >= 0 & a%%2 == 0) # Returns rows with positive b & evennumbered a

    You can also easily perform database join operations, using merge:B fun fun(3, 1, 2, 3)[1] 30> fun(5, 1, 2, 3)[1] 78

    A more complicated example of a function. First, create some data:set.seed(123) # allow reproducible random numbersa

  • 7/31/2019 Xhn R Resumen

    15/39

    new

  • 7/31/2019 Xhn R Resumen

    16/39

    and compare the redshifts of clusters observed with ACIS-S & ACIS-I:plot(z ~ det, data=A)

    You can define your own factor categories by partitioning a numeric vector of data intodiscrete bins using cut() , as shown here:

    Converting a numeric vector into factorsSplit cluster redshift range into 2 bins of equal width (nearer & further clusters), and assigneach z point accordingly; create new column of data frame with the bin assignments(A$z.bin ):A$z.bin

  • 7/31/2019 Xhn R Resumen

    17/39

    http://www.sr.bham.ac.uk/~ajrs/R/r-access_data.html

    Data structures in R All R objects have a type or mode, as well as a class, which can be determined with typeof , mode

    & class . Vector

    Vectors are the basic structure and come in the following atomic modes (data types):

    numeric, integer, character, logical, complex, raw

    These modes have corresponding functions which test if an object is of that mode ( is , e.g.is.numeric ) and convert an object to that mode ( as , e.g. as.character )

    You can assemble and combine vectors using the often-used function c . Note that vectorsmust consist of values of the same data type:

    c(1, "a", TRUE) # all values coerced to characterlist(1, "a", TRUE) # preserves different types (see below)

    Factors

    Factors encode categorical data, and are an extremely useful and efficient way of handlingcategories with multiple entries. Note that R often coerces character data to a factor type bydefault (e.g. when using read.table ). Also have is.factor & as.factor .

    chars

  • 7/31/2019 Xhn R Resumen

    18/39

    A

  • 7/31/2019 Xhn R Resumen

    19/39

    planets["Mars", "mass"] # show the mass of Mars; same as planets[4, 1]rownames(planets) mean(mass))subset(planets, mass > 1e24 & semimajoraxis < 1e12 )# Adding new columns to the data frame:planets

  • 7/31/2019 Xhn R Resumen

    20/39

    read.fortran : fixed-format data files using Fortran-style format specifications read.DIF : Data Interchange Format (DIF) for data frames from single spreadsheets read.dcf : Debian Control File format read.ftable / write.ftable : flat contingency tables readBin ; writeBin : binary data

    readChar ; writeChar : character strings readLines ; writeLines : lines write : write data to a file dump : write text representation of an object dget ; dput : read or recreate an ASCII representation of an R object

    Other packages for R data input / outputThere are a number of separate packages for reading and writing data in different formats. Thefollowing are some common examples; see the R Data Import/Export manual for more information.

    library(help="foreign") # Minitab, S, SAS, SPSS, Stata,Systat, dBase, Octave format

    RODBC package : for database sources supporting an ODBC interface gdata package : various tools, e.g. read.xls for reading data from Excel xtable package : Export tables to LaTeX or HTML

    Entering & editing data within R data.entry ; de : conveniet GUI tools for entering data edit : use text editor to modify an R object fix : invoke edit to change & overwrite an R object

    Saving & loading R objects save writes an external representation of R objects to the specified file; these can then be

    loaded back into R using load , e.g.

    a

  • 7/31/2019 Xhn R Resumen

    21/39

    loadhistory(file="my.Rhistory") ls & objects lists the objects currently defined apropos finds objects with names containing the specified string, e.g.

    apropos("max")[1] "cummax" "max" "max.col" "pmax" "pmax.int" "promax"[7] "varimax" "which.max"

    One of the most important aspects of computing with data is the ability to manipulate it, to enablesubsequent analysis and visualization. R offers a wide range of tools for this purpose. Note that the

    plyr package provides an even more powerful and convenient means of manipulating and processingdata, which I hope to describe in later updates to this page.

    Add and remove data http://www.sr.bham.ac.uk/~ajrs/R/r-manipulate_data.htmlFirst create a data frame, then remove a column and create a new one:A

  • 7/31/2019 Xhn R Resumen

    22/39

    colnames(AB2) # } note thecolnames(AB3) # } difference

    the identical column names for A & B are rendered unambiguous when usingas.data.frame(c(A, B)) , by appending .1 to the 2nd data frame column names. It does thisusing make.unique , which is useful if you need to generate unique elements, given a vector

    containing duplicated character strings.

    do.call

    do.call constructs and executes a function call from a name or a function and a list of argumentsto be passed to it. It is an extremely useful task, that can be used to join together data data framesstored in a list, for example:l

  • 7/31/2019 Xhn R Resumen

    23/39

    On a related theme, the following set operators are also useful:intersect(1:5, 3:8)union(1:5, 3:8)

    and to identify or remove duplicate entries from a vector:x

  • 7/31/2019 Xhn R Resumen

    24/39

    x y1 a -0.5604756 0.52810552 b -0.2301775 0.89241903 c 1.5587083 0.5514350

    Now stack the columns:> stack(A)

    values ind1 -0.5604756 x2 -0.2301775 x3 1.5587083 x4 0.5281055 y5 0.8924190 y6 0.5514350 y

    # NB, the "ind" column is now a factor:> class(stack(A)$ind)[1] "factor"

    But note that the column a is lost in the stacking:

    > unstack(stack(A))x y

    1 -0.5604756 0.52810552 -0.2301775 0.89241903 1.5587083 0.5514350

    There is also a function reshape which converts between so-called long and wide format data (i.e.columns stacked below each other vs. columns arranged beside each other). However, thedocumentation for reshape is remarkably opaque! A much more convenient function is melt from

    the excellent reshape package:install.packages("reshape")require(melt)melt(A) # retains column "a", unlike "stack(A)"

    Truncating and rounding data Create a set of Gaussian-distributed random numbers:

    set.seed(123) # allow reproducible random numbersx

  • 7/31/2019 Xhn R Resumen

    25/39

    To truncate data above and below some thresholds (e.g. set all values below zero to zero and above 1to 1):x2

  • 7/31/2019 Xhn R Resumen

    26/39

    View data structure http://www.sr.bham.ac.uk/~ajrs/R/r-show_data.html Before you do anything else, it is important to understand the structure of your data and that of

    any objects derived from it.A

  • 7/31/2019 Xhn R Resumen

    27/39

    Other summaries:x

  • 7/31/2019 Xhn R Resumen

    28/39

    4 non-CC S 0.03636667

    #--Show mean values of a few quantitied, for each cctype:aggregate(. ~ cctype, data=a[c("cctype", "z", "kT", "Z", "S01", "index")],mean)

    You can also apply multi-number summaries:> aggregate( index ~ cctype, data=a, FUN=range)

    cctype index.1 index.21 CC 0.714 1.1202 non-CC 0.283 0.944

    Base graphics http://www.sr.bham.ac.uk/~ajrs/R/r-plot_data.htmlFor a basic introduction, see the "getting started" page here . Base graphics are very flexible and allowa great deal of customisation, with many individual functions available. However, they lack acoherent underlying framework and, for visualizing highly structured data, are outclassed by lattice and ggplot2 .

    Quick reference info:demo("graphics") # Demonstration of graphics in R?plot # Help page for main plot function?par # Help page for changing graphical parameters?layout # Help page on plot arrangementexample("pch") # Point style examplescolours() # List pre-defined named colours?plotmath # Help page on plotting maths symbolsdemo(plotmath)

    Useful plotting functions:lines, points, abline, curve, text, rug, legendsegments, arrows, polygonlocator, identify # For interacting with plots

    Create some data for plotting:x

  • 7/31/2019 Xhn R Resumen

    29/39

    Plot symbols and colours can be specified as vectors, to allow individual specification for each point.R uses recycling of vectors in this situation to determine the attributes for each point, i.e. if the lengthof the vector is less than the number of points, the vector is repeated and concatenated to match thenumber required.

    Single plot symbol (see "?points" for more) and colour (type "colours()" or "colors()" for thefull list of predefined colours):

    plot(x, y, pch=2, col="red") # Hollow trianglesplot(x, y, pch=c(3, 20), col=c("red", "blue")) # Blue dots; red "+" signsplot(x, y, pch=1:20) # Different symbol for each point

    Create vector of contiguous colours in a rainbow palette:col

  • 7/31/2019 Xhn R Resumen

    30/39

    Specifying panels of different sizes:layout(matrix(1:4, 2, 2), heights=c(2, 1)); layout.show(4)replicate(4, plot(x, x)) # Repeat plot 4 times

    Plotting a function or equationThe function curve allows you to plot equations or complex functions, either on their own, or added toan existing plot (with add=T).

    Plot some analytic expressions:curve(x^2)curve(x^1) # "curve(x)" fails! (can also use "curve(I(x))")curve(x^2+log10(x)-sin(x)) # Can use arithmeticcurve(dnorm) # Normal distribution for mean=0, standard deviation=1curve(x^3-x+1, from=-10, to=10, lty=2) # Specify range & use dashed line

    Plot a function, with specified arguments:curve(dnorm(x, mean=1, sd=2), from=-10, to=10)

    curve provides the function to be plotted with a vector of x-axis values called x with which tocalculate the corresponding y-axis data. If the argument of your function is not called x (e.g. r) , thenyou need to use the following syntax: curve(myfun(r=x)) . The following example illustratesthis with a plot of several blackbody curves.

    First, define a function for the Planck blackbody law to calculate the radiation intensity as afunction of wavelength (lambda, in microns) and temperature (Temp, in Kelvin):

    blackbody

  • 7/31/2019 Xhn R Resumen

    31/39

    Interacting with the plot To find out the coordinates at a particular position on a graph, type: locator() then left

    click with the mouse any number of times within the axes and right click to end; the R promptwill then return and a list will be printed with the X and Y coordinates of the positions clicked.You can retain this information by repeating the above, but with A

  • 7/31/2019 Xhn R Resumen

    32/39

    A$giant 1e25, "Giant", "Not giant")

    Lattice can now separately handle the different categories, either by using group , to usedifferent plotting symbols etc. within the same panel, e.g.:dotplot(reorder(name, sma) ~ log10(sma), data=A,

    xlab="log10 semi-major axis (m)", groups=giant, auto.key=TRUE)

    ...or by conditioning on a categorical variable, to plot separate panels for each dataset:dotplot(reorder(name, sma) ~ log10(sma) | giant, data=A,

    xlab="log10 semi-major axis (m)", auto.key=TRUE)

    You can also easily plot linear regression models (from lm ) for each group category, using thetype argument:xyplot(sma ~ mass, data=A, groups=giant, scales=list(log=TRUE),

    type=c("g", "p", "r"), auto.key=list(lines=TRUE))##---Other "type" arguments:# "g" = show gridlines# "p" = points# "l" = lines (join the dots)# "r" = linear regression model# "smooth" = locally-weighted regression using "loess"#

    Lattice offers a very quick route to visualize a set of properties conditioned on one or morefactors. For example, to show boxplots of 4 different quantities in separate panels, with each

    panel comparing values in different categories:file

  • 7/31/2019 Xhn R Resumen

    33/39

    While R is best known as an environment for statistical computing, it is also a great tool for numericalanalysis (optimization, integration, interpolation, matrix operations, differential equations etc). Here isa flavour of the capabilities that R offers in analysing data.For a basic introduction, see the analysis section of the getting started page. For a more thoroughoverview of regression using R in an astronomical context, see this tutorial here .

    Numerical Analysis in R http://www.sr.bham.ac.uk/~ajrs/R/r-analyse_data.html

    Parameter optimization To find the minimum value of a function within some interval, use optimize (optimise

    is a valid alias):fun

  • 7/31/2019 Xhn R Resumen

    34/39

  • 7/31/2019 Xhn R Resumen

    35/39

    Now, compare with the prediction from a smoothing spline:f

  • 7/31/2019 Xhn R Resumen

    36/39

    Matrix crossproduct:x

  • 7/31/2019 Xhn R Resumen

    37/39

    #--Demonstrate function:> mystat(A, 1:nrow(A)) # same as "coef(m)"(Intercept) x

    0.3100925 0.9839554

    > set.seed(123) # allow reproducible random numbers> mystat(A, sample(nrow(A), replace=TRUE)) # result for a single

    resample(Intercept) x0.6143148 0.9416338

    #--Run full set of "N.boot" bootstrap resamples:N.boot coef(summary(m))

    Estimate Std. Error t value Pr(>|t|)(Intercept) 0.3100925 0.46199915 0.6711972 5.106173e-01

    x 0.9839554 0.03856694 25.5129205 1.389147e-15#--Or, quantify the difference by comparing the ratios:> sd(b$t) / coef(summary(m))[, 2] # close to 1 in each case(Intercept) x

    0.9686099 1.0318067 A quicker version of the above example, using the method described in Section 4.3.1 from

    Chambers & Hastie, 1992 (see References section in ?lm for book details). This methodexploits the fact that lm does a certain amount of initial processing prior to the actualregression (using lm.fit ), and this represents a substantial overhead that need only be

    performed once (and need not be replicated during each bootstrap resampling iteration).

    # following Section 4.3.1 from Chambers & Hastie (1992):m

  • 7/31/2019 Xhn R Resumen

    38/39

    mystat.fast

  • 7/31/2019 Xhn R Resumen

    39/39

    straight line)plot(b, index=1) # parameter "a"plot(b, index=2) # parameter "b"

    #--Now compare the standard errors on the model parameters from# the bootstrap resampling with those from the normal summary method:> b # print results of bootstrap

    ORDINARY NONPARAMETRIC BOOTSTRAP

    Call:boot(data = B, statistic = mystat, R = N.boot)

    Bootstrap Statistics :original bias std. error

    t1* 3.986804 -0.02582234 0.1361342t2* 2.040456 0.02679389 0.1332876

    > summary(m) # print standard errors (see "?summary.nls")Formula: y ~ a * log10(x) + b

    Parameters:Estimate Std. Error t value Pr(>|t|)

    a 3.9868 0.1299 30.70 < 2e-16 ***b 2.0405 0.1275 16.01 4.33e-12 ***---Signif. pres: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

    Residual standard error: 0.1998 on 18 degrees of freedom

    Number of iterations to convergence: 1Achieved convergence tolerance: 1.234e-07

    #--Or, quantify the difference by comparing the ratios:sd(b$t) / coef(summary(m))[, 2] # close to 1 in each case

    a b1.048229 1.045583

    For further information, you can find out more about how to access , manipulate , summarise , plot andanalyse data using R .

    http://www.sr.bham.ac.uk/~ajrs/R/r-access_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-access_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-manipulate_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-manipulate_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-show_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-show_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-plot_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-plot_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-analyse_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/index.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/index.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-access_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-manipulate_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-show_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-plot_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/r-analyse_data.htmlhttp://www.sr.bham.ac.uk/~ajrs/R/index.html