一、R的變量類型
也可以說是數據存儲方式,有:
Vector: 一維陣列
Matrics: 二維陣列,其中所有元素是同一數據類型。
factor: 種類變量,可使用levels函數來規定種類變量的各級別的名稱。例如:levels(factor_vector) <- c("name1", "name2",...)
Dataframe:二維陣列,每一列中的元素是同一數據類型,不同列的數據類型可以不同。
List : 一個List中可包含多個類型對象,包括List本身。
二、常用函數
seq(from,to,by): Generate sequences, by specifying the from, to and by arguments.
rep(): Replicate elements of vectors and lists.
sort(): Sort a vector in ascending order. Works on numerics, but also on character strings and logicals.
rev(): Reverse the elements in a data structures for which reversal is defined.
str(): Display the structure of any R object.
append(): Merge vectors or lists.
is.*(): Check for the class of an R object.
as.*(): Convert an R object from one class to another.
unlist(): Flatten (possibly embedded) lists to produce a vector.
三、apply函數家族
通過apply函數對結構化的數據實現某些操作,對向量(vector)或者列表(list)按照元素或元素構成的子集合進行迭代。個人認為相當於一種批處理操作。
lapply(X, FUN, ...)
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
lapply和sapply將一個函數應用於一個list或者vector, 區別在於lapply以列表(list)形式返回結果,而sapply將輸出結果簡化為一個向量或者矩陣。
vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)
vapply
類似於sapply
,但是提供了參數FUN.VALUE
用以指明返回值的形式,即返回值可以有預定義類型,因此更安全。
四、正則表達式(regular expression)
正則表達式不是R的專屬內容,用於描述/匹配一個文本集合的表達式。通常被用來檢索、替換那些符合某個模式(規則)的文本。
1.元字符(metacharacter)
一些特殊的字符在正則表達式中不在用來描述它自身,它們在正則表達式中已經被“轉義”,這些字符稱為元字符。
常用元字符如下:
2、字符串匹配查詢函數
查詢功能的函數主要有grep、grepl, 主要區別在於其輸出結果格式不同,共同點是都包含正則表達式pattern和文本X這兩個參數。
grepl(pattern, x) which returns TRUE
when a pattern is found in the corresponding character string.
grep(pattern, x) which returns a vector of indices of the character strings that contains the pattern.
grep僅返回匹配項的下標,而grepl返回所有的查詢結果,並用邏輯向量表示有沒有找到匹配
3、字符串替換函數
模式替換函數主要有sub和gsub,二者的區別在於sub函數只替換文本中第一個匹配的元素,gsub則針對X中所有匹配元素。
sub(pattern, replacement, x)
gsub(pattern, replacement, x)