Example: quiz answers

R Reference Card

R Reference Cardby Tom Short, EPRI PEAC, 2004-11-07 Granted to the public domain. See for the source and latestversion. Includes material fromR for Beginnersby Emmanuel Paradis (withpermission).Getting helpMost R functions have online (topic)documentation ontopic? ("topic")search the help systemapropos("topic")the names of all objects in the search list matchingthe regular expression topic ()start the HTML version of helpstr(a)display the internal *str*ucture of an R objectsummary(a)gives a summary ofa, usually a statistical summary but it isgenericmeaning it has different operations for different classes ofals()show objects in the search path; specifypat="pat"to search on ()str() for each variable in the search pathdir()show files in the current directorymethods(a)shows S3 methods ofamethods(class=class(a))lists all the methods to handle objects ofclass aInput and outputload()load the datasets written withsavedata(x)loads specified data setslibrary(x)load add-on (file)reads a file in table format and creates a dataframe from it; the default separatorsep=""is any whitespace; useheader=TRUEto read the first line as a header of column names.

R Reference Card by Tom Short, EPRI PEAC, tshort@epri-peac.com 2004-11-07 Granted to the public domain. See www.Rpad.org for the source and latest

Tags:

  Reference, Card, Pire, Reference card

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of R Reference Card

1 R Reference Cardby Tom Short, EPRI PEAC, 2004-11-07 Granted to the public domain. See for the source and latestversion. Includes material fromR for Beginnersby Emmanuel Paradis (withpermission).Getting helpMost R functions have online (topic)documentation ontopic? ("topic")search the help systemapropos("topic")the names of all objects in the search list matchingthe regular expression topic ()start the HTML version of helpstr(a)display the internal *str*ucture of an R objectsummary(a)gives a summary ofa, usually a statistical summary but it isgenericmeaning it has different operations for different classes ofals()show objects in the search path; specifypat="pat"to search on ()str() for each variable in the search pathdir()show files in the current directorymethods(a)shows S3 methods ofamethods(class=class(a))lists all the methods to handle objects ofclass aInput and outputload()load the datasets written withsavedata(x)loads specified data setslibrary(x)load add-on (file)reads a file in table format and creates a dataframe from it; the default separatorsep=""is any whitespace; useheader=TRUEto read the first line as a header of column names.

2 Prevent character vectors from being converted to fac-tors; ""to prevent"#"from being interpreted asa comment; useskip=nto skipnlines before reading data; see thehelp for options on row naming, NA treatment, and ("filename",header=TRUE)id. but with defaults set forreading comma-delimited ("filename",header=TRUE)id. but with defaults setfor reading tab-delimited (file,widths,header=FALSE,sep=" ", )read a table offixedwidthformatted data into a ;widthsis an integer vector, giving the widths of the fixed-width fieldssave(file,..)saves the specified objects (..) in the XDR platform-independent binary (file)saves all objectscat(.., file="", sep=" ")prints the arguments after coercing tocharacter;sepis the character separator between argumentsprint(a, ..)prints its arguments; generic, meaning it can have differ-ent methods for different objectsformat(x,..)format an R object for pretty (x,file="", , ,sep=" ")printsxafter converting to a data frame; ifquoteisTRUE,character or factor columns are surrounded by quotes (");sepis thefield separator;eolis the end-of-line separator;nais the string formissing values; add a blank column header toget the column headers aligned correctly for spreadsheet inputsink(file)output tofile, untilsink()Most of the I/O functions have afileargument.

3 This can often be a charac-ter string naming a file or a ""means the standard input oroutput. Connections can include files, pipes, zipped files, and R windows, the file connection can also be used withdescription ="clipboard". To read a table copied from Excel, usex <- ("clipboard")To write a table to the clipboard for Excel, (x,"clipboard",sep="\t", )For database interaction, see packagesRODBC,DBI,RMySQL,RPgSQL, andROracle. See packagesXML,hdf5,netCDFfor reading other file creationc(..)generic function to combine arguments with the default forming avector; withrecursive=TRUE descends through lists combining allelements into one vectorfrom:togenerates a sequence; : has operator priority; 1:4 + 1 is 2,3,4,5 seq(from,to)generates a sequenceby=specifies increment;length=specifies desired lengthseq(along=x)generates1, 2, .., length(along); useful forforloopsrep(x,times)replicatex times; useeach=to repeat each el-ement ofx eachtimes;rep(c(1,2,3),2)is 1 2 3 1 2 3;rep(c(1,2,3),each=2)is 1 1 2 2 3 (.)

4 Create a data frame of the named or unnamedarguments; (v=1:4,ch=c("a","B","c","d"),n=10);short er vectors are recycled to the length of the longestlist(..)create a list of the named or unnamed arguments;list(a=c(1,2),b="hi",c=3i);arr ay(x,dim=)arraywithdatax;specifydimensio nslikedim=c(3,4,2); elements ofxrecycle ifxis not long enoughmatrix(x,nrow=,ncol=)matrix; elements ofxrecyclefactor(x,levels=)encodes a vectorxas a factorgl(n,k,length=n*k,labels=1:n)gener ate levels (factors) by spec-ifying the pattern of their levels;kis the number of levels, andnisthe number of ()a data frame from all combinations of the supplied vec-tors or factorsrbind(..)combine arguments by rows for matrices, data frames, andotherscbind(..)id. by columnsSlicing and extracting dataIndexing vectorsx[n] nthelementx[-n]allbutthenthelementx[1:n] firstnelementsx[-(1:n)]elements fromn+1to the endx[c(1,4,2)]specific elementsx["name"]element named"name"x[x > 3]all elements greater than 3x[x > 3 & x < 5]all elements between 3 and 5x[x %in% c("a","and","the")]elements in the given setIndexing listsx[n]list with elementsnx[[n]] nthelement of the listx[["name"]]element of the list named"name"x$ matricesx[i,j]element at rowi, columnjx[i,]rowix[,j]columnjx[,c(1,3)]co lumns 1 and 3x["name",]row named"name"Indexing data frames (matrix indexing plus the following)x[["name"]]column named"name"x$ (x), (x), (x), (x), (x), (x).

5 Convert type; for a complete list, usemethods(as)Variable (x), (x), (x), (x), (x), (x), (x),..test for type; for a complete list, usemethods(is)length(x)number of elements inxdim(x)Retrieve or set the dimension of an object;dim(x) <- c(3,2)dimnames(x)Retrieve or set the dimension names of an objectnrow(x)number of rows;NROW(x)is the same but treats a vector as a one-row matrixncol(x)andNCOL(x)id. for columnsclass(x)get or set the class ofx;class(x) <- "myclass"unclass(x)remove the class attribute ofxattr(x,which)get or set the attributewhichofxattributes(obj)get or set the list of attributes ofobjData selection and (x)returns the index of the greatest element (x)returns the index of the smallest element ofxrev(x)reverses the elements ofxsort(x)sorts the elements ofxin increasing order; to sort in decreasingorder:rev(sort(x))cut(x,breaks )dividesxinto intervals (factors);breaksis the numberof cut intervals or a vector of cut pointsmatch(x, y)returns a vector of the same length thanxwith the elementsofxwhich are iny(NAotherwise)which(x == a)returns a vector of the indices ofxif the comparison op-eration is true (TRUE), in this example the values ofifor whichx[i]== a(the argument of this function must be a variable of mode logi-cal)choose(n, k)computes the combinations ofkevents amongnrepetitions=n!

6 /[(n k)!k!] (x)suppresses the observations with missing data (NA) (sup-presses the corresponding line ifxis a matrix or a data frame) (x)returns an error message ifxcontains at least oneNAunique(x)ifxis a vector or a data frame, returns a similar object but withthe duplicate elements suppressedtable(x)returns a table with the numbers of the differents values ofx(typically for integers or factors)subset(x, ..)returns a selection ofxwith respect to criteria (..,typically comparisons:x$V1 < 10); ifxis a data frame, the optionselectgives the variables to be kept or dropped using a minus signsample(x, size)resample randomly and without replacementsizeele-ments in the vectorx, the optionreplace = TRUE allows to resamplewith (x,margin=)table entries as fraction of marginal tableMathsin,cos,tan,asin,acos,atan,atan 2,log,log10,expmax(x)maximum of the elements ofxmin(x)minimum of the elements ofxrange(x)id. thenc(min(x), max(x))sum(x)sum of the elements ofxdiff(x)lagged and iterated differences of vectorxprod(x)product of the elements ofxmean(x)mean of the elements ofxmedian(x)median of the elements ofxquantile(x,probs=)sample quantiles corresponding to the given prob-abilities (defaults to 0.)

7 25,.5,.75,1) (x, w)mean ofxwith weightswrank(x)ranks of the elements ofxvar(x)orcov(x)variance of the elements ofx(calculated onn 1); ifxisa matrix or a data frame, the variance-covariance matrix is calculatedsd(x)standard deviation ofxcor(x)correlation matrix ofxif it is a matrix or a data frame (1 ifxis avector)var(x, y)orcov(x, y)covariance betweenxandy, or between thecolumns ofxand those ofyif they are matrices or data framescor(x, y)linear correlation betweenxandy, or correlation matrix if theyare matrices or data framesround(x, n)rounds the elements ofxtondecimalslog(x, base)computes the logarithm ofxwith basebasescale(x)ifxis a matrix, centers and reduces the data; to center only usethe optioncenter=FALSE, to reduce onlyscale=FALSE(by defaultcenter=TRUE, scale=TRUE)pmin(x,y,..)a vector whichith element is the minimum ofx[i],y[i], ..pmax(x,y,..)id. for the maximumcumsum(x)a vector whichith element is the sum fromx[1]tox[i]cumprod(x)id. for the productcummin(x)id.

8 For the minimumcummax(x)id. for the maximumunion(x,y),intersect(x,y),setdiff (x,y),setequal(x,y), (el,set) set functionsRe(x)real part of a complex numberIm(x)imaginary partMod(x)modulus;abs(x)is the sameArg(x)angle in radians of the complex numberConj(x)complex conjugateconvolve(x,y)compute the several kinds of convolutions of two se-quencesfft(x)Fast Fourier Transform of an arraymvfft(x)FFT of each column of a matrixfilter(x,filter)applies linear filtering to a univariate time series orto each series separately of a multivariate time seriesMany math functions have a logical specify miss-ing data (NA) (x)transposediag(x)diagonal%*%matrix multiplicationsolve(a,b)solvesa %*% x = bforxsolve(a)matrix inverse ofarowsum(x)sum of rows for a matrix-like object;rowSums(x)is a fasterversioncolsum(x),colSums(x)id. for columnsrowMeans(x)fast version of row meanscolMeans(x)id. for columnsAdvanced data processingapply(X,INDEX,FUN=)a vector or array or list of values obtained byapplying a functionFUNto margins (INDEX) ofXlapply(X,FUN)applyFUNto each element of the listXtapply(X,INDEX,FUN=)applyFUNto each cell of a ragged array givenbyXwith indexesINDEXby(data,INDEX,FUN)applyFUNto data framedatasubsetted byINDEX merge(a,b)merge two data frames by common columns or row namesxtabs(a b,data=x)a contingency table from cross-classifying factorsaggregate(x,by,FUN)splits the data framexinto subsets, computessummary statistics for each, and returns the result in a convenientform;byis a list of grouping elements, each as long as the variablesinxstack(x.)

9 Transform data available as separate columns in a dataframe or list into a single columnunstack(x, ..)inverse ofstack()reshape(x, ..)reshapes a data frame between wide format withrepeated measurements in separate columns of the same record and long format with the repeated measurements in separate records;use(direction= wide ) or(direction= long )Stringspaste(..)concatenate vectors after converting to character;sep=is thestring to separate terms (a single space is the default);collapse=isan optional string to separate collapsed resultssubstr(x,start,stop)substrings in a character vector; can also as-sign, assubstr(x, start, stop) <- valuestrsplit(x,split)splitxaccording to the substringsplitgrep(pattern,x)searches for matches topatternwithinx; see?regexgsub(pattern,replacement,x)repl acement of matches determinedby regular expression matchingsub()is the same but only replacesthe first (x)convert to lowercasetoupper(x)convert to uppercasematch(x,table)a vector of the positions of first matches for the elementsofxamongtablex %in% tableid.

10 But returns a logical vectorpmatch(x,table)partial matches for the elements ofxamongtablenchar(x)number of charactersDates and TimesThe classDatehas dates without dates and times, includ-ing time zones. Comparisons ( >),seq(), anddifftime()are allows+and .?DateTimeClassesgives more information. Seealso (s) (s)convert to the respective class;format(dt)converts to a string representation. The default stringformat is 2001-02-21 . These accept a second argument to specify aformat for conversion. Some common formats are:%a,%AAbbreviated and full weekday ,%BAbbreviated and full month of the month (01 31).%HHours (00 23).%IHours (01 12).%jDay of year (001 366).%mMonth (01 12).%MMinute (00 59).%pAM/PM as decimal number (00 61).%UWeek (00 53); the first Sunday as day 1 of week (0 6, Sunday is 0).%WWeek (00 53); the first Monday as day 1 of week without century (00 99). Don t with (output only.) Offset from Greenwich;-0800is 8 hours west (output only.)


Related search queries