0% found this document useful (0 votes)
17 views

R Program Cheat Sheet 1

The document provides information about vectors in R including how to create, access, and manipulate them. It covers common vector functions and operations like sorting, reversing, selecting elements. It also discusses loops, conditional statements, and functions. The last section describes reading and writing data in R.

Uploaded by

ram.pharmacy0020
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

R Program Cheat Sheet 1

The document provides information about vectors in R including how to create, access, and manipulate them. It covers common vector functions and operations like sorting, reversing, selecting elements. It also discusses loops, conditional statements, and functions. The last section describes reading and writing data in R.

Uploaded by

ram.pharmacy0020
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Vectors Programming

Base R Creating Vectors For Loop While Loop


Cheat Sheet Join elements into
c(2, 4, 6) 2 4 6 for (variable in sequence){ while (condition){
a vector
Do something Do something
An integer
2:6 2 3 4 5 6
Getting Help sequence } }

Accessing the help files A complex Example Example


seq(2, 3, by=0.5) 2.0 2.5 3.0
sequence
?mean for (i in 1:4){ while (i < 5){
Get help of a particular function. rep(1:2, times=3) 1 2 1 2 1 2 Repeat a vector
j <- i + 10 print(i)
help.search(‘weighted mean’)
Repeat elements print(j) i <- i + 1
Search the help files for a word or phrase. rep(1:2, each=3) 1 1 1 2 2 2
of a vector
help(package = ‘dplyr’) } }
Find help for a package. Vector Functions
More about an object If Statements Functions
sort(x) rev(x)
Return x sorted. Return x reversed. if (condition){ function_name <- function(var){
str(iris)
table(x) unique(x) Do something
Get a summary of an object’s structure. Do something
See counts of values. See unique values. } else {
class(iris) Do something different return(new_variable)
Find the class an object belongs to. } }
Selecting Vector Elements
Example Example
Using Libraries By Position if (i > 3){ square <- function(x){
install.packages(‘dplyr’) x[4] The fourth element. print(‘Yes’)
squared <- x*x
Download and install a package from CRAN. } else {
print(‘No’) return(squared)
library(dplyr) x[-4] All but the fourth.
} }
Load the package into the session, making all
its functions available to use. x[2:4] Elements two to four.
Reading and Writing Data
dplyr::select All elements except
x[-(2:4)] Input Ouput Description
Use a particular function from a package. two to four.

Elements one and Read and write a delimited text


data(iris) df <- read.table(‘file.txt’) write.table(df, ‘file.txt’)
x[c(1, 5)] file.
five.
Load a built-in dataset into the environment.
By Value Read and write a comma
Working Directory Elements which df <- read.csv(‘file.csv’) write.csv(df, ‘file.csv’) separated value file. This is a
x[x == 10] special case of read.table/
are equal to 10.
write.table.
getwd()
All elements less
Find the current working directory (where x[x < 0]
than zero.
Read and write an R data file, a
inputs are found and outputs are sent). load(‘file.RData’) save(df, file = ’file.Rdata’)
x[x %in% Elements in the set file type special for R.

setwd(‘C://file/path’) c(1, 2, 5)] 1, 2, 5.


Change the current working directory.
Named Vectors Greater than is.na(a)
a == b Are equal a > b Greater than a >= b Is missing
or equal to
Use projects in RStudio to set the working Conditions
Element with Less than or is.null(a)
x[‘apple’] a != b Not equal a < b Less than a <= b Is null
directory to the folder you are working in. equal to
name ‘apple’.

RStudio® is a trademark of RStudio, Inc. • CC BY Mhairi McNeill • [email protected] Learn more at web page or vignette • package version • Updated: 3/15
Types Matrixes Strings Also see the stringr library.
m <- matrix(x, nrow = 3, ncol = 3) paste(x, y, sep = ' ')
Converting between common data types in R. Can always go Join multiple vectors together.
Create a matrix from x.
from a higher value in the table to a lower value.
paste(x, collapse = ' ') Join elements of a vector together.
m[2, ] - Select a row t(m)
grep(pattern, x) Find regular expression matches in x.
as.logical TRUE, FALSE, TRUE Boolean values (TRUE or FALSE). Transpose
w
ww m %*% n gsub(pattern, replace, x) Replace matches in x with a string.
m[ , 1] - Select a column
Integers or floating point
as.numeric 1, 0, 1
numbers.
ww
w Matrix Multiplication toupper(x) Convert to uppercase.
ww solve(m, n)
w tolower(x) Convert to lowercase.
Character strings. Generally ww
w m[2, 3] - Select an element Find x in: m * x = n
as.character '1', '0', '1' nchar(x)
preferred to factors. Number of characters in a string.

'1', '0', '1', Character strings with preset


w
ww
as.factor levels. Needed for some
ww
w
levels: '1', '0' Lists Factors
statistical models.

l <- list(x = 1:5, y = c('a', 'b')) factor(x) cut(x, breaks = 4)


A list is collection of elements which can be of different types. Turn a vector into a factor. Can Turn a numeric vector into a
Maths Functions set the levels of the factor and factor but ‘cutting’ into
log(x) Natural log. sum(x) Sum. l[[2]] l[1] l$x l['y'] the order. sections.
New list with New list with
exp(x) Exponential. mean(x) Mean. Second element Element named
only the first only element
of l. x. Statistics
max(x) Largest element. median(x) Median. element. named y.
min(x) Smallest element. quantile(x) Percentage
lm(x ~ y, data=df) prop.test
quantiles. Also see the t.test(x, y)
Data Frames Linear model. Preform a t-test for Test for a
round(x, n) rank(x) dplyr library.
Round to n decimal Rank of elements. difference between difference
places. glm(x ~ y, data=df) between
df <- data.frame(x = 1:3, y = c('a', 'b', 'c')) means.
Generalised linear model. proportions.
signif(x, n) Round to n var(x) The variance. A special case of a list where all elements are the same length.
significant figures. pairwise.t.test
List subsetting summary aov
Preform a t-test for
cor(x, y) Correlation. sd(x) The standard x y Get more detailed information Analysis of
paired data.
deviation. out a model. variance.
df$x df[[2]]
1 a
Variable Assignment Distributions
2 b Understanding a data frame
> a <- 'apple' Random Density Cumulative
Quantile
> a See the full data Variates Function Distribution
3 c View(df)
[1] 'apple' frame. Normal rnorm dnorm pnorm qnorm
See the first 6 rpois dpois ppois qpois
Matrix subsetting head(df) Poison
rows.
The Environment Binomial rbinom dbinom pbinom qbinom
df[ , 2]
ls() List all variables in the nrow(df) cbind - Bind columns. Uniform runif dunif punif qunif
environment. Number of rows.

rm(x) Remove x from the ncol(df)


Plotting Also see the ggplot2 library.
environment. df[2, ] Number of
columns.
rm(list = ls()) Remove all variables from the rbind - Bind rows. plot(x) plot(x, y) hist(x)
environment. Values of x in Values of x Histogram of
dim(df)
Number of order. against y. x.
You can use the environment panel in RStudio to
df[2, 2] columns and
browse variables in your environment. rows.
Dates See the lubridate library.

RStudio® is a trademark of RStudio, Inc. • CC BY Mhairi McNeill • [email protected] • 844-448-1212 • rstudio.com Learn more at web page or vignette • package version • Updated: 3/15

You might also like