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

R BasicCommands

This document is a comprehensive R commands cheatsheet covering various topics such as setting the working directory, operators, packages, data structures (vectors, matrices, lists, data frames), plotting, handling missing values, and string manipulation. It provides specific commands and examples for each topic to assist users in using R effectively. The cheatsheet serves as a quick reference guide for R programming tasks and functions.

Uploaded by

Spyros Veronikis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

R BasicCommands

This document is a comprehensive R commands cheatsheet covering various topics such as setting the working directory, operators, packages, data structures (vectors, matrices, lists, data frames), plotting, handling missing values, and string manipulation. It provides specific commands and examples for each topic to assist users in using R effectively. The cheatsheet serves as a quick reference guide for R programming tasks and functions.

Uploaded by

Spyros Veronikis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

R commands cheatsheet

Set working directory setwd("F:/Docs/ebooks/R/basics")


Get working directory getwd()
List files in directory dir()
Get structure type of object str(obj)
Get class of object class(obj)
Get type of object typeof(obj)
Clear several variables rm(var1, var2, …)
Clear workspace rm(list = ls(all = TRUE))
Operators
Addition 1+2
Subtraction 1-2
Multiplication 1*2
Division 1/2
Exponent 1^2
Modulus 10 %% 8 # returns 2
Integer division 10 %/% 8 # returns 1
Negation !
Logical AND A & B (alt. A && B)
Logical OR A | B (alt. A || B)
Comparison operators < <= > >= == !=
Packages The packages that are included with the R distribution are visible as
subdirectories of your library directory in your R installation tree, as
in /usr/lib/R/library.

Display installed packages installed.packages()


Which packages are currently loaded? .path.package() or (.packages())
Get a list of packages loaded by default getOption("defaultPackages")
See all available (installed) packages (.packages(all.available=TRUE)) or library()
Load a package (e.g., MASS) library(MASS)
require(MASS)
Install a new package install.packages("mvtnorm","C:/Program Files/R/R-2.15.2/library")
install.packages(c("tree", "maptree"))

Get the library (folder) of installed .Library


packages
Remove installed package(s) remove.packages(c("tree", "maptree"), .Library)
Update installed package(s) update.packages(MASS)

List the functions in a package help(package=MASS)

List datasets in package named “datasets” library(help="datasets")


library(help=MASS)

1
Vectors (set of 1 type structures)
Create a vector a_vector= 1:5
b_vector = seq(from=12, to= 31, by= 3)
myvector = c(3,2,1)
c(1, list(T, "hello"))
Replicate values 4 times rep(T, 4)
Get element from vector myvector[1] # returns 3
Concatenate vector elements new_vector = paste(myvector)
Add column/row cbind(), rbind()
Get length of vector length(myvector)
Get certain elements from vector myvector[c(1,3)]
myvector[1:2]

Exclude 2nd element from vector Let vector be V = c(10,20,30,40). Then V[-2] returns 10 30 40

Assign names to vector elements x <- c(1,2,3)


names(x) <- c(‘a’, ‘b’, ‘c’)
Matrices (2D vectors)
Get information on matrices ?matrix
Create a 2D matrix mymatrix = matrix(data = c(1,2,3,4), nrow= 2, byrow=T)
Get matrix dimensions dim(mymatrix), nrow(mymatrix), ncol(mymatrix)
Set/get rownames/colnames rownames(Matrix), colnames(Matrix)

Indexing matrix elements mymatrix[1,1]


mymatrix[ , 1:2]
mymatrix[c(1,2), ]
filtered <- mymatrix[ ,2] >= 5

Find indices of values greater than 2 Let: M = matrix(data= c(5,2,9,-1,10,11), ncol=2, byrow=F)
which(M > 2) # returns 1 3 5 6 (column-wise)

Matrix multiplication A %*% A


Multiplication by a scalar A * 3
Matrix addition A + A
Lists (set of several type structures)
Create a list of numbers & strings mylist <- list(item1=1, item2= c("Peter","Pan") , item3= T)
List indexing mylist[2], mylist[["item2"]], mylist[[2]] all return "Peter", "Pan"
mylist[[2]][2] returns "Pan"
Add list element mylist$item4 <- "new element"
Get length of a list length(mylist)

2
Data Frames
Create a data frame data <- data.frame(list(kids=c("Jack","Jill"),ages=c(12,10)))
data = read.csv("2010_07.txt", header=F,
sep= "", dec=".", na.strings= "NA",
nrows= 31, skip= 11, blank.lines.skip= T)
Data frame indexing data[ ,c(1,3,5)]
Returns objects from object x, described x[i]
by i. i may be an integer vector,
character vector (of object names), or
logical vector. Does not allow partial
matches. When used with lists, returns
a list. When used with vectors, returns a
vector.

Returns a single element of x, matching i. x[[i]]


i may be an integer or character vector of
length 1. Allows partial matches (with
exact=FALSE option).

Get attributes of data frame attributes(data)


Get column-names of data frame names(dataFrame)
Get summary of data frame summary(data)
Get column values from data frame data$kids
Get first values on data frame head(data)
Print variable’s content print(var)
Help
Get help on a command help(sqrt)
?abs

Get examples of use example(sqrt)


Search for an expression help.search(“2 dimensional plots»)
Get information on an R-package help(package=MASS)
Plots
Create a 2D plot x <- seq(from=0, to=6, by=.5)
y <- x^2;
plot(x,y, type=’s’,
xlab="X-values", ylab="Y-values", main="Parabolica",
xlim= c(0, max(x)), ylim= c(min(y), max(y)) )
plot(x,y, type=’l’, lwd= 2,
xlab="X-values", ylab="Y-values",
main="Parabolica", xlim= c(0, max(x)), ylim= c(min(y), max(y)) )
points(x,y, pch= 20, cex= 0.5)

Create a new plot window windows()


Create subplots par(mfrow= c(1,2)), par(mfrow= c(1,1))
Create horizontal line abline(b= 2, h=T) or abline(a= 10, v=T) or abline(a=1, b=0)

3
Missing Values
Math operations on missing values x <- c(88, NA, 12, 168)
mean(x) # will not work because of missing value
mean(x, na.rm=T) # this will fix it
Determine where there are missing values
Remove missing values is.na(x)
y <- x[!is.na(x)]
Functions
Create a function oddcount <- function(x){
k <- 0 # assign a value to k
for (n in x)
if (n %% 2 == 1){
k <- k+1
}
return(k)
}
Read data from file
Read all lines from textfile.txt content <- readLines("textfile.txt")
Get a list of connections (e.g., file, ?connection
url, gzfile, etc)

Read 1 line from file Linehandler <- file("textfile.txt", "r")


readLines(Linehandler, n=1)

Find if there is any value satisfying a x = seq(from= 1, to= 10, by=2)


condition any(x >3) # it returns TRUE
all(x == T) # it returns FALSE
Logical statements
IF … ELSE condition if (var > value){
Code block A
} else {
Code block B
}
Repeat-until repeat {if (i > 25) break else {print(i); i <- i + 5;}}
Do-While while (i <= 25) {print(i); i <- i + 5}
FOR-loop for (i in seq(from=5, to=25, by=5)) print(i)
Apply function to list tapply()
sapply()
lapply(mylist, mean)
String manipulation &
Regular Expressions

Search for a specified substring pattern grep("Pole", c("Equator", "North Pole", "South Pole")) # returns 2 3
in a vector of x strings
Get the length of a string nchar("South Pole") # returns 10
Concatenate several strings into a long paste("North", "pole") # returns "North pole"
4
one
Assembe a string from parts, in a sprintf("Temperature ranges from %.2f to %.2f Celsius", minTEMP, maxTEMP)
formatted manner
Return the substring in the given substr("Equator", 3, 5) # returns "uat"
character position range start:stop

Split a string x into an R-list of strsplit("31-03-2013", split= "-") # returns "31" "03" "2013"
substrings, based on another string split
in x.

Find the character position of the FIRST regexpr(PATTERN, TEXT), e.g.,


instance of PATTERN within TEXT regexpr("uat", "Equator") # returns 3

Find the character position(s) for ALL gregexpr(PATTERN, TEXT), e.g.,


instance(s) of PATTERN within TEXT regexpr("iss", "Mississipi") # returns 2 5

Find any character of a given set "[au]" # Find any of the characters in brackets
E.g., grep("[au]", c("Equator", "North Pole", "South Pole"))
Returns 1 3 (i.e., "Equator" and "South Pole"
Find any single character in a string "o.e" # Find any character in place of dot
grep("o.e", c("Equator", "North Pole", "South Pole"))
Returns 2 3 (i.e., "North Pole" and "South Pole"
Find multiple single characters in a "N..t" # Find any two characters between ‘N’ and ‘t’
string E.g., grep("N..t", c("Equator", "North Pole", "South Pole"))
Returns 2 (i.e., "North Pole")

Find a metacharacter in a string "\metacharacter", e.g., "\?"


Other metacharacters are: backshlash(\), dot(.), etc
E.g., grep("\\.", c("mytext", "image", "report.pdf"))
Returns 3 denoting that the 3rd item in the vector is the only one with a
filename extention
The second backslash is an escape character for the first backslash
(which is used for the dot (.) metacharacter)

Find character(s) in list of STRINGS which(STRINGS = "W")


grep(".SW", STRINGS)

You might also like