



Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!




Public domain, v2.0 2012-12-24.V 2 by Matt Baggott, [email protected] 1 by Tom Short, [email protected] from
R for Beginners
by permission of
help(topic)
documentation on topic ?topic
same as above; special chars need quotes: forexample
help.search(
ʺ topic
ʺ )^ search the help system; same
as^ ??topic apropos(
ʺ topic
ʺ )^ the names of all objects in the search list matching the regular expression“topic” help.start()
start the HTML version of help summary(x)
generic function to give a “summary” of x, often a statistical one str(x)
display the internal structure of an R object ls()^ show objects in the search path; specify pat="pat" to search on a pattern ls.str()
str^ for each variable in the search path dir()
show files in the current directory methods(x)
shows S3 methods of x methods(class=class(x))
lists all the methods to
handle objects of class x findFn()
searches a database of help packages for functions and returns a data.frame (
sos )
task
views
are summaries of R resources for
task domains at: cran.r-project.org/web/viewsCan be accessed via
ctv^ package
cran.r-project.org/doc/FAQ/R-FAQ.html R^ Functions
for^ Regression
Analysis
, by Vito
Ricci: cran.r-project.org/doc/contrib/Ricci-refcard-regression.pdf R^ Functions
for^ Time
Series
Analysis
, by Vito
Ricci: cran.r-project.org/doc/contrib/Ricci-refcard-ts.pdf R^ Reference
Card
for^ Data
Mining
, by Yanchang
Zhao: www.rdatamining.com/docs/R-refcard-data-mining.pdf R^ Reference
Card
, by Jonathan Baron: cran.r-
project.org/doc/contrib/refcard.pdf
Left assignment, binary ‐ >^
Right assignment, binary =^
Left assignment, but not recommended << ‐^
Left assignment in outer lexical scope; notfor beginners $^
List subset, binary ‐^
Minus, can be unary or binary +^
Plus, can be unary or binary ~^
Tilde, used for model formulae :^
Sequence, binary (in model formulae:interaction) ::^
Refer to function in a package, i.e,pkg::function; usually not needed *^
Multiplication, binary /^
Division, binary ^^
Exponentiation, binary %x%
Special binary operators, x can bereplaced by any valid name %%
Modulus, binary %/%
Integer divide, binary %*%
Matrix product, binary %o%
Outer product, binary %x%
Kronecker product, binary %in%
Matching operator, binary (in modelformulae: nesting) !^ x^
logical negation, NOT x x^ &^ y^
elementwise logical AND x^ &&
y^
vector logical AND x^ |^ y
elementwise logical OR x^ || y^
vector logical OR xor(x,
y)^
elementwise exclusive OR <^
Less than, binary >^
Greater than, binary ==^
Equal to, binary >=^
Greater than or equal to, binary <=^
Less than or equal to, binary Packages^ install.packages(“pkgs”,
lib)
download and install
pkgs from repository (lib) or other externalsource update.packages
checks for new versions and
offers to install library(pkg)
loads pkg, if pkg is omitted it lists packages detach(
ʺ package:pkg
ʺ )^ removes pkg from memory
Indexing
vectors x[n]
nth element
x[ ‐ n]
all but the nth element
x[1:n]
first n elements
x[ ‐ (1:n)]
elements from n+1 to end
x[c(1,4,2)]
specific elements
x[ ʺ name
element named "name"
x[x^ >
all elements greater than 3
x[x^ >
x^ <^
all elements between 3 and 5
x[x^ %in%
c( ʺ a
ʺ , ʺ if ʺ )]^ elements in the given set
Indexing
lists x[n]
list with elements n
x[[n]]
nth element of the list
x[[ ʺ name
element named "name"
x$name
as above (w. partial matching)
Indexing
matrices x[i,j]
element at row i, column j
x[i,]
row i
x[,j]
column j
x[,c(1,3)]
columns 1 and 3
x[ ʺ name
row named "name"
Indexing
matrices
data
frames
(same
as^ matrices
plus
the^
following) X[[ ʺ name
column named "name"
x$name
as above (w. partial matching)
R^ data
object
data(x)
loads specified data set; if no arg is given itlists all available data sets save(file,...)
saves the specified objects (...) in XDR platform-independent binary format save.image(file)
saves all objects
load(file)
load datasets written with save Database
Useful packages:
interface between R and
relational DBMS;
access to databases
through the JDBC interface;
RMySQL
interface to
MySQL database;
ODBC database access;
ROracle
Oracle database interface driver;
RpgSQL
interface to PostgreSQL database;
RSQLite
SQLite
interface for R
Other
file
read.table(file),
read.csv(file), read.delim(“file”),
read.fwf(“file”)
read a
file using defaults sensible for atable/csv/delimited/fixed-width file and create adata frame from it. write.table(x,file),
write.csv(x,file)
saves x after
converting to a data frame txtStart
and^
txtStop
: saves a transcript of
commands and/or output to a text file( TeachingDemos
download.file(url)
from internet
url.show(url)
remote input
cat(...,
file=
ʺʺ ,^ sep=
ʺ ʺ )^ prints the arguments after
coercing to character; sep is the characterseparator between arguments print(x,
...)^ prints its arguments; generic, meaning itcan have different methods for different objects format(x,...)
format an R object for pretty printing sink(file)
output to file, until sink() Clipboard
File connections of functions can also be used to readand write to the clipboard instead of a file. Mac OS:
x^ < ‐
read.delim(pipe(“pbpaste”))
Windows:
x^ < ‐
read.delim(
ʺ clipboard
See also
read.clipboard
( psych
Data
creation c(...)^ generic function to combine arguments with thedefault forming a vector; with recursive=TRUEdescends through lists combining all elementsinto one vector from:to
generates a sequence; “:” has operatorpriority; 1:4 + 1 is “2,3,4,5” seq(from,to)
generates a sequence by= specifies increment; length= specifies desired length seq(along=x)
generates 1, 2, ..., length(along); useful in for loops rep(x,times)
replicate x times; use each to repeat “each” element of x each times; rep(c(1,2,3),2) is1 2 3 1 2 3;
rep(c(1,2,3),each=2)
is 1 1 2 2 3 3
data.frame(...)
create a data frame of the named or unnamed arguments data.frame (v=1:4, ch=c("a","B","c","d"), n=10); shorter vectors arerecycled to the length of the longest list(...)
create a list of the named or unnamedarguments; list(a=c(1,2),b="hi", c=3);
array(x,dim=)
array with data x; specify
dimensions like dim=c(3,4,2); elements of xrecycle if x is not long enough matrix(x,nrow,ncol)
matrix; elements of x recycle
factor(x,levels) encodes a vector x as a factor gl(n,
k,^ length=n*k,
labels=1:n)
generate levels
(factors) by specifying the pattern of their levels;k is the number of levels, and n is the number ofreplications expand.grid()
a data frame from all combinations of the supplied vectors or factors Data
conversion as.array(x),
as.character(x),
as.data.frame(x),
as.factor(x),
as.logical(x),
as.numeric(x),
convert type; for a complete list, use methods(as) Data
information is.na(x),
is.null(x),
is.nan(x);
is.array(x),
is.data.frame(x),
is.numeric(x),
is.complex(x),
is.character(x)
; for a complete
list, use
methods(is) x^ prints x head(x),
tail(x)
returns first or last parts of an object
summary(x)
generic function to give a summary
str(x)
display internal structure of the data length(x)
number of elements in x dim(x)
Retrieve or set the dimension of an object; dim(x) < ‐^ c(3,2) dimnames(x)
Retrieve or set the dimension names of an object nrow(x),
ncol(x)
number of rows/cols;
NROW(x),
NCOL(x)
is the same but treats a vector as a one-row/col matrix class(x)
get or set the class of x;
class(x)
ʺ myclass
unclass(x)
removes the class attribute of x attr(x,which)
get or set the attribute which of x
attributes(obj)
get or set the list of attributes of obj
Data
selection
and
manipulation
which.max(x),
which.min(x)
returns the index of
the greatest/smallest element of x rev(x)
reverses the elements of x sort(x)
sorts the elements of x in increasing order; tosort in decreasing order:
rev(sort(x))
cut(x,breaks)
divides x into intervals (factors); breaks is the number of cut intervals or a vector of cutpoints match(x,
y)^ returns a vector of the same length as x with the elements of x that are in y (NAotherwise) which(x
==^ a)
returns a vector of the indices of x if the comparison operation is true (TRUE), in thisexample the values of i for which x[i] == a (theargument of this function must be a variable ofmode logical) choose(n,
k)^ computes the combinations of k events among n repetitions = n!/[(n
−^ k)!k!]
na.omit(x)
suppresses the observations with missing data (NA) na.fail(x)
returns an error message if x contains at least one NA complete.cases(x)
returns only observations (rows)
with no NA unique(x)
if x is a vector or a data frame, returns a similar object but with the duplicates suppressed table(x)
returns a table with the numbers of thedifferent values of x (typically for integers orfactors) split(x,
f)^ divides vector x into the groups based on f subset(x,
...)^ returns a selection of x with respect to criteria (..., typically comparisons: x$V1 < 10); ifx is a data frame, the option select gives variablesto be kept (or dropped, using a minus) sample(x,
size)
resample randomly and without replacement size elements in the vector x, forsample with replacement use: replace = TRUE sweep(x,
margin,
stats)
transforms an array by
sweeping out a summary statistic prop.table(x,margin)
table entries as fraction of
marginal table xtabs(a
b,data=x)
a contingency table from cross-
classifying factors replace(x,
list,
values)
replace elements of x listed in
index with values
Some
statistical
tests
cor.test(a,b)
test correlation
;^ t.test()
t test;
prop.test(),
binom.test()
sign test
;^ chisq.test()
chi-
square test
;^ fisher.test()
Fisher exact test
friedman.test()
Friedman test
;^ ks.test()
Kolmogorov-Smirnov test... use
help.search(
ʺ test
formulas Formulas use the form: response ~ termA + termB ...Other formula operators are: 1
intercept, meaning depdendent variable hasits mean value when independent variablesare zeros or have no influence :^
interaction term *^
factor crossing, a*b is same as a+b+a:b ^^
crossing to the specified degree, so(a+b+c)^2 is same as (a+b+c)*(a+b+c) ‐^
removes specified term, can be used toremove intercept as in resp ~ a - 1 %in%
left term nested within the right: a + b%in% a is same as a + a:b I()^
operators inside parens are used literally:I(a*b) means a multiplied by b |^
conditional on, should be parenthetical Formula-based modeling functions commonly takethe arguments: data, subset, and na.action. Model
functions aov(formula,
data)
analysis of variance model
lm(formula,
data)
fit linear models;
glm(formula,
family,
data)
fit generalized linear
models; family is description of error distributionand link function to be used; see ?family nls(formula,
data)
nonlinear least-squares
estimates of the nonlinear model parameters lmer(formula,
data)
fit mixed effects model
( lme
); see also
lme()
( nlme
anova(fit,
data...)
provides sequential sums of
squares and corresponding F-test for objects contrasts(fit,
contrasts
view contrasts
associated with a factor; to set use: contrasts(fit,
how.many)
< ‐^ value
glht(fit,
linfct)
makes multiple comparisons using a linear function linfct (
mutcomp
summary(fit)
summary of model, often w/ t-values
confint(parameter)
confidence intervals for one or
more parameters in a fitted model. predict(fit,...)
predictions from fit
df.residual(fit)
returns residual degrees of freedom
coef(fit)
returns the estimated coefficients (sometimes with standard-errors) residuals(fit)
returns the residuals
deviance(fit)
returns the deviance
fitted(fit)
returns the fitted values logLik(fit)
computes the logarithm of the likelihood and the number of parameters AIC(fit),
BIC(fit)
compute Akaike or Bayesian
information criterion influence.measures(fit)
diagnostics for lm & glm
approx(x,y)
linearly interpolate given data points; x can be an xy plotting structure spline(x,y)
cubic spline interpolation loess(formula)
fit polynomial surface using local fitting optim(par,
fn,^ method
=^ c( ʺ Nelder
‐ Mead
general-purpose optimization; par is initialvalues, fn is function to optimize (normallyminimize) nlm(f,p)
minimize function f using a Newton-type algorithm with starting values p Flow
control if(cond)
expr if(cond)
cons.expr
else
alt.expr
for(var
in^ seq)
expr
while(cond)
expr
repeat
expr
break next switch Use braces {} around statements ifelse(test,
yes,
no)^
a value with the same shape as
test filled with elements from either yes or no do.call(funname,
args)
executes a function call
from the name of the function and a list ofarguments to be passed to it Writing
functions function(
arglist
)^ expr function definition,
missing
test whether a value was specified as an argument to a function require
load a package within a function << ‐^ attempts assignment within parent environment
before search up thru environments on.exit(expr)
executes an expression at function end
return(value)
or^ invisible
sep,
collapse)
concatenate vectors
after converting to character; sep is a string toseparate terms; collapse is optional string toseparate “collapsed” results; see also str_c below substr(x,start,stop)
get or assign substrings in a
character vector. See also str_sub below strsplit(x,split)
split x according to the substring split
grep(pattern,x)
searches for matches to pattern within x; see
?regex gsub(pattern,replacement,x)
replace pattern in x
using regular expression matching; sub() is similarbut only replaces the first occurrence. tolower(x),
toupper(x)
convert to lower/uppercase
match(x,table)
a vector of the positions of first matches for the elements of x among table x^ %in%
table
as above but returns a logical vector
pmatch(x,table)
partial matches for the elements of x among table nchar(x)
stringr
package
provides a nice interface for string
functions: str_detect
detects the presence of a pattern; returns a logical vector str_locate
locates the
first position of a pattern; returns
a numeric matrix with col start and end.(str_locate_all locates all matches) str_extract
extracts text corresponding to the
first
match; returns a character vector (str_extract_allextracts all matches) str_match
extracts “capture groups” formed by () from the^ fi
rst match; returns a character matrix with one column for the complete match and one column foreach group str_match_all
extracts “capture groups” from all matches ; returns a list of character matrices str_replace
replaces the first matched pattern; returns a character vector str_replace_all
replaces all matches.
str_split_fixed
splits string into a
fixed number of
pieces based on a pattern; returns character matrix str_split
splits a string into a variable number of pieces; returns a list of character vectors str_c
joins multiple strings, similar to paste str_length
gets
length of a string, similar to nchar
str_sub
extracts substrings from character vector,similar to substr
Class
Date
is dates without times. Class
POSIXct
is
dates and times, including time zones. Class timeDate
in^ timeDate
includes financial centers.
lubridate
package
is great for manipulating
time/dates and has 3 new object classes:^ interval
class:
time between two specific instants. Create with
new_interval()
or subtract two
times. Access with
int_start()
and^
int_end()
duration
class:
time spans with exact lengths new_duration()
creates generic time span
that can be added to a date; other functionsthat create duration objects start with d:dyears(), dweeks()… period
class:
time spans that may not have a consistent lengths in seconds; functionsinclude: years(), months(), weeks(), days(),hours(), minutes(), and seconds() ymd(date,
tz),^
mdy(date,
tz),^
dmy(date,
tz)
transform character or numeric dates toPOSIXct object using timezone tz (
lubridate
Other
time
packages:
zoo, xts, its
do irregular time
series;
TimeWarp
has a holiday database from 1980+;
timeDate
also does holidays;
tseries
for analysis and
computational finance;
forecast
for modeling
univariate time series forecasts;
fts^ for faster
operations;
tis^ for time indexes and time indexed series, compatible with FAME frequencies. Date
and
time
formats
are specified with:
%a, %A Abbreviated and full weekday name.%b, %B Abbreviated and full month name.%d^
Day of the month (01-31) %H^
Hours (00-23) %I^
Hours (01-12) %j^
Day of year (001-366) %m^
Month (01-12) %M^
Minute (00-59) %p^
AM/PM indicator %S^
Second as decimal number (00-61) %U^
Week (00-53); first Sun is day 1 of wk 1 %w^
Weekday (0-6, Sunday is 0) %W
Week (00-53); 1st Mon is day 1 of wk 1 %y^
Year without century (00-99) Don’t use %Y^
Year with century %z^
(output only) signed offset from Greenwich;-0800 is 8 hours west of %Z^
(output only) Time zone as a character string
ggplot
package. They have
limited interoperability. Base, grid, and lattice arecovered here.
ggplot
needs its own reference sheet.
arguments
for^ base
plots:
add=FALSE
if TRUE superposes the plot on the previous one (if it exists) axes=TRUE
if FALSE does not draw the axes and the box type=
ʺ p ʺ^ specifies the type of plot, "p": points, "l":lines, "b": points connected by lines, "o": sameas previous but lines are over the points, "h":vertical lines, "s": steps, data are represented bythe top of the vertical lines, "S": same asprevious but data are represented by the bottomof the vertical lines xlim=,
ylim=
specifies the lower and upper limits of the axes, for example with xlim=c(1, 10) orxlim=range(x) xlab=
,^ ylab=
annotates the axes, must be variables of mode character main= main title, must be avariable of mode character sub=
sub-title (written in a smaller font) Base
plot
functions plot(x)
plot of the values of x (on the y-axis) orderedon the x-axis plot(x,
y)^ bivariate plot of x (on the x-axis) and y (onthe y-axis) hist(x)
histogram of the frequencies of x barplot(x)
histogram of the values of x; use horiz=TRUE for horizontal bars dotchart(x)
if x is a data frame, plots a Cleveland dot plot (stacked plots line-by-line and column-by-column) boxplot(x)
“box-and-whiskers” plot stripplot(x)
plot of the values of x on a line (an alternative to boxplot() for small sample sizes) coplot(x˜y
|^ z) bivariate plot of x and y for each value or interval of values of z interaction.plot
(f1, f2,^ y)
if f1 and f2 are factors,
plots the means of y (on the y-axis) with respectto the values of f1 (on the x-axis) and of f2(different curves); the option fun allows tochoose the summary statistic of y (by default
fun=mean) matplot(x,y)
bivariate plot of the first column of x vs. the first one of y, the second one of x vs. thesecond one of y, etc. fourfoldplot(x)
visualizes, with quarters of circles, the association between two dichotomousvariables for different populations (x must be anarray with dim=c(2, 2, k), or a matrix withdim=c(2, 2) if k=1) assocplot(x)
Cohen-Friendly graph showing the deviations from independence of rows andcolumns in a two dimensional contingency table mosaicplot(x)
‘mosaic’ graph of the residuals from a log-linear regression of a contingency table pairs(x)
if x is a matrix or a data frame, draws allpossible bivariate plots between the columns of x plot.ts(x)
if x is an object of class "ts", plot of x with respect to time, x may be multivariate but theseries must have the same frequency and dates ts.plot(x)
same as above but if x is multivariate the series may have different dates and must havethe same frequency qqnorm(x)
quantiles of x with respect to the values expected under a normal distribution qqplot(x,
y)^ diagnostic plotr of quantiles of y vs. quantiles of x; see also qqPlot in
cars
package
and distplot in
vcd^
package
contour(x,
y,^ z)
contour plot (data are interpolated to draw the curves), x and y must be vectors andz must be a matrix so that dim(z)= c(length(x),length(y)) (x and y may be omitted). See alsofilled.contour, image, and persp symbols(x,
y,^ ...)
draws, at the coordinates given by
x and y, symbols (circles, squares, rectangles,stars, thermometers or “boxplots”) with sizes,colours... are specified by supplementaryarguments termplot(mod.obj)
plot of the (partial) effects of a
regression model (mod.obj) colorRampPalette
creates a color palette (use:
colfunc <- colorRampPalette(c("black","white")); colfunc(10) Low
‐ level
base
plot
arguments
points(x,
y)^ adds points (the option type= can be used) lines(x,
y)^ same as above but with lines text(x,
y,^ labels,
...)^ adds text given by labels at