输入ls()或者objects()命令列举出当前内存中的对象
> ls()
[1] "x" "y"
> objects()
[1] "x" "y"
> rm(y)
> v<-c(1,2,3,4,5)
> v
[1] 1 2 3 4 5
> length(v)
[1] 5
> mode(v)
[1] "numeric"
> v<-c(4,5,6,"Ruby")
> mode(v)
[1] "character"
所有向量可以包含一个特殊值,即NA,该值代表缺失值:
> u<-c(4,6,NA,2)
> u
[1] 4 6 NA 2
> x<-vector()
> mode(x)
[1] "logical"
> length(x)
[1] 0
> x<-c(1,4,9)
> sqrt(x)
[1] 1 2 3
> y<-c(1,2,3)
> x+y
[1] 2 6 12
> v1<-c(1,2,3,4)
> v2<-c(1,2)
> v1+v2
[1] 2 4 4 6
> v1<-c(1,2,3)
> v1+v2
[1] 2 4 4
Warning message:
In v1 + v2 :
longer object length is not a multiple of shorter object length
因子:用水平来表示所有可能的取值
> g<-c("f","m","m","m","f","m","f","m","f","f")
> g
[1] "f" "m" "m" "m" "f" "m" "f" "m" "f" "f"
> g<-factor(g)
> g
[1] f m m m f m f m f f
Levels: f m
table()函数也可以用于获取多个因子的交叉表
> table(g) f,m出现次数为5
g
f m
5 5
> a<-factor(c('a','a','j','j','a','a','a','j','a','j'))
> table(a,g)
g
a f m
a 4 2
j 1 3
计算列联表的边际和相对频率(参数1表示第一个维度,即每一行的元素个数6,4。参数2表示第二个维度,即每一列的元素个数5,5)
> t<-table(a,g)
> margin.table(t,1)
a
a j
6 4
> margin.table(t,2)
g
f m
5 5
> prop.table(t,1)
g
a f m
a 0.6666667 0.3333333
j 0.2500000 0.7500000
> prop.table(t,2)
g
a f m
a 0.8 0.4
j 0.2 0.6
> prop.table(t)
g
a f m
a 0.4 0.2
j 0.1 0.3
生成序列:
产生1~100的序列:
x<-1:100
> x
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
[20] 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
[39] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
[58] 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
[77] 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
[96] 96 97 98 99 100
利用函数seq()生成实数序列:
> seq(-4,1,0.5)
[1] -4.0 -3.5 -3.0 -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0
> seq(from=1,to=5,length=4)
[1] 1.000000 2.333333 3.666667 5.000000
> seq(from=1,to=5,length=2)
[1] 1 5
> seq(from=-2,by=0.2,length=10)
[1] -2.0 -1.8 -1.6 -1.4 -1.2 -1.0 -0.8 -0.6 -0.4 -0.2
> rep(5,10)
[1] 5 5 5 5 5 5 5 5 5 5
> rep("hi",3)
[1] "hi" "hi" "hi"
> rep(1:2,3)
[1] 1 2 1 2 1 2
> rep(1:2,each=3)
[1] 1 1 1 2 2 2