对象间的转化
向量转化为矩阵
> V<-1:5
> V
[1] 1 2 3 4 5
> as.matrix(V)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
因子转化为数值
> fac<-factor(c(1,10))
> fac
[1] 1 10
Levels: 1 10
> as.numeric(fac)
[1] 1 2
> fac1<-factor(c("xiaowang","dawang"))
> fac1
[1] xiaowang dawang
Levels: dawang xiaowang > as.numeric(fac1) [1] 2 1
矩阵转化为数据框
> meaing<-matrix(data=3, nr = 3, nc = 5)
> meaing
[,1] [,2] [,3] [,4] [,5]
[1,] 3 3 3 3 3
[2,] 3 3 3 3 3
[3,] 3 3 3 3 3
> as.data.frame(meaing)
V1 V2 V3 V4 V5
1 3 3 3 3 3
2 3 3 3 3 3
3 3 3 3 3 3
矩阵转化为列表
> meaing<-matrix(1:10, nr = 2, nc = 5)
> meaing
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> as.list(meaing)
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 4
[[5]]
[1] 5
[[6]]
[1] 6
[[7]]
[1] 7
[[8]]
[1] 8
[[9]]
[1] 9
[[10]]
[1] 10
查看对象类型和长度
对象类型:
——猜错试错法:is.FUN的形式,返回TRUE或FALSE
[1] 1 2 3 4
> is.vector(x)
[1] TRUE
> is.vector(c("qingchen","xiari"))
[1] TRUE
——直接查看:class查看第一层类别,mode查看第二层类别,typeof查看第3层类别
对象长度:
——向量,因子:length,也可以查看其它对象类型
> length(c(1:8))
[1] 8
> length(gl(3,6))
[1] 18
> gl(3,6)
[1] 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3
Levels: 1 2 3
——矩阵,数据框:nrow查询行数,ncol查询列数
> meaing<-matrix(1:10, nr = 2, nc = 5)
> meaing
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> nrow(meaing)
[1] 2
> ncol(meaing)
[1] 5
——数组:dim维数
> Mat<-array(1:5,c(2,4,2))
> Mat
, , 1
[,1] [,2] [,3] [,4]
[1,] 1 3 5 2
[2,] 2 4 1 3
, , 2
[,1] [,2] [,3] [,4]
[1,] 4 1 3 5
[2,] 5 2 4 1
> dim(Mat)
[1] 2 4 2
——对象概览:str,attributes,所有对象的通用查询函数
> str(Mat1)
num [1:2, 1:4, 1:2] 5 5 5 5 5 5 5 5 5 5 ...
> attributes(Mat1)
$dim
[1] 2 4 2