R BasicCommands
R BasicCommands
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
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)
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.
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)
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 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")