登录
首页精彩阅读R的变量类型和常用函数
R的变量类型和常用函数
2017-05-23
收藏

R的变量类型和常用函数

一、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)


数据分析咨询请扫描二维码

客服在线
立即咨询