R:数据结构学习

R语言数据结构与基本运算

一.数据类型

Numeric 数值类型

Character 字符类型

Logical 逻辑类型

Complex 复数类型

Raw 二进制 原始类型

NA missing value

NAN not a number如:log-1

Inf  无穷 如:1/0

二.数据对象

Vector 向量 c() seq1,10.by=2

Matrix 矩阵

Array 数组

Factor 因子

List 列表

Frame 数据框

2.1字符向量

nchar(x) 计算x中的字符数量

substr(x, start, stop):求子串

grep(pattern, x):正则表达式匹配

sub(pattern, replacement, x):替换

strsplit(x, split):分割为字符向量

toupper(x):转换为大写

tolower(x):转换为小写

 

向量的运算:

rep()函数重复一个对象

ength(x)长度

min(x)

max(x)

which.min(x) which.max(x)

最小值下标 最大值下标

range(x)范围

mean(x)均值

median(x)中位数

var(x)方差

sd(x)标准差

 

向量的常用函数:

um(x)求和

rev(x)倒置

sort(x)排序

rank(x)排序位置

prod(x)连乘

append()追加

append(c(1,2,3,4),5:8)

append(c(1,2,3,4),5:8,after=3)

 

向量的索引:

x[x<5]

x[2:4]

x[c(2,4)]

x[-c(2,4)] 负号表示去掉这些下标

 

2.2 矩阵

matrix(data=NA, nrow=1, ncol=1, byrow=false, dimnames=NULL)

 

t(A)A的转置矩阵

 

使用A[row,col]检索矩阵元素,其中rowcol可以是数字或向量,

若不输入代表所有

 

apply(X,margin,fun) margin = 1,按行;margin = 2,按列

 

使用如下函数提取矩阵的上、下三角

lower.tri(x, diag=FALSE)

upper.tri(x, diag=FALSE)

 

A  * B   对应元素相乘

A  %*% B 矩阵相乘,必须满足矩阵乘条件

t(A)  %*% B ======crossprob(A,B),计算效率更高

 

A为方阵:diag(A)A的对角线

A为向量:diag(A)生成以A为对角线的方阵

A为数字:diag(A)生成A阶单位阵

 

det(A) 求方阵A的行列式

solve(A)  A为方阵 |A| 0 求矩阵A的逆矩阵

eigen(A)  求特征值和特征向量

 

2.3 数组

一维数组:向量vector

二维数组:矩阵matrix

2.4 因子

actor (x=character(), levels, labels=levels, exclude=NA, ordered = is.ordered(x)

其中levels用来指定因子的水平,

labels指定水平的名字,

exclude表示需要排除的水平

ordered用来决定因子的水平是否有序

有序因子可以通过ordered ()函数产生

 score_o <- ordered(score,levels=c("D","C","B","A"))

2.5 列表

向量、矩阵和数组要求所有元素都必须是同一类型的数据。

若含有不同的数据类型,可以采用list

> x <- c(1,1,2,2,3,3,3)

> y <- c("F","M","M","F","F","F","M")

> z <- c(80,85,92,76,61,95,83)

> mylist <- list(class=x,gender=y,score=z)

2.6 数据框

数据框data.frame

是一种特殊的list,列同类型

每行代表一个观测

进行统计分析最有用的数据类型

> x <- c(1,1,2,2,3,3,3)

> y <- c("F","M","M","F","F","F","M")

> z <- c(80,85,92,76,61,95,83)

> student <- data.frame(class=x,gender=y,score=z)

> student$score

[1] 80 85 92 76 61 95 83

> student[[3]]

[1] 80 85 92 76 61 95 83

 

数据框的检索

> student[student$score>80,]

  class gender score

2     1      M    85

3     2      M    92

6     3      F      95

7     3      M    83

> student[student$gender=="M",]

  class gender score

2     1      M    85

3     2      M    92

7     3      M    83

attach(student),直接列名访问

detach(student),取消绑定

tapply(X, INDEX, FUN = NULL)

X:待统计向量

INDEX:分组依据,一般为因子

FUN:统计函数

> attach(student)

> score

[1] 80 85 92 76 61 95 83

> tapply(score,class,sum)

  1   2   3

165 168 239

> tapply(score,gender,sum)

  F   M

312 260

> detach(student)

 

posted @ 2017-03-12 19:26  工科女的瞎忙活  阅读(158)  评论(0编辑  收藏  举报