R语言之书2.3.3

2019-12-31 10:10:40 浏览数 (1)

#章节1 新手入门

getwd()

setwd("D:/R")

setwd("D:R")

library("MASS")

?mean

??"mean"

?mean

q()

#章节2.1基础数学

sqrt(x=9) #计算非负值的平方根

2^(2 1)-4 64^((-2)^(2.25-1/4)) #-2要加括号

log(x=243,base=3) #对数

exp(x=3) #指数

#练习

(6*2.3 42)/(3^(4.2-3.62))

sqrt((mean(25.2,12,16.44,15.3,18.6))/2)

log(x=0.3,base=exp(1)) #exp(1)=e=2.718

-0.00000000423546322 #-4.235463e-09

exp(log(x=0.3,base=exp(1)))

#章节2.2分配对象

x<--5

x=x 1

mynumber=45.2

y<-mynumbe

ls() #查看当前工作空间所包含的内容

#练习

x<-(3^2)*(4^(1/8))

x<-x/2.33

y<--8.2*(10^(-13))

x*y

#章节2.3向量

myvec<-c(1,3,1,42) #创建向量

myvec

foo<-32.1

myvec2<-c(3,-3,2,3,45,1e 03,64^0.5,2 (3-1)/9.44,foo)

myvec2

myvec3<-c(myvec,myvec2)

myvec3

#序列

3:27 #从3开始逐项加1到27为止

foo<-5.3

bar<-foo:(-47 1.5) #从5.3开始逐项减1

ba

seq(from=3,to=27,by=3) #序列函数seq

seq(from=3,to=27,length.out=40) #40个等间隔的数

myseq<-seq(from=foo,to=(-47 1.5),by=-2.4) #递减序列

myseq

myseq2<-seq(from=foo,to=(-47 1.5),length.out=5)

myseq2

rep(x=1,times=4) #重复函数rep

rep(x=c(3,62,8.3),times=3) #times的值为重复x的次数

rep(x=c(3,62,8.3),each=2) #each的值为重复元素的个数

rep(x=c(3,62,8.3),times=3,each=2)

foo<-4

c(3,8.3,rep(x=32,times=foo),seq(from=-2,to=1,length.out=foo 1))

sort(x=c(2.5,-1,-10,3.44),decreasing=FALSE) #排序函数sort

sort(x=c(2.5,-1,-10,3.44),decreasing=TRUE)

foo<-seq(from=4.3,to=5.5,length.out=8)

foo

bar<-sort(x=foo,decreasing=TRUE)

ba

sort(x=c(foo,bar),decreasing=FALSE)

length(x=c(3,2,8,1)) #长度函数length

length(x=5:13)

foo<-4

bar<-c(3,8.3,rep(x=32,times=foo),seq(from=-2,to=1,length.out=foo 1))

length(x=bar)

#练习

x<-seq(from=5,to=-11,by=-0.3)

x

x<-sort(x,decreasing=FALSE)

x

x2<-sort(rep(x=c(-1,3,-5,7,-9),times=2,each=10),decreasing=FALSE)

x2

length(x2)

x<-seq(from=6,to=12)

y<-rep(x=5.3,times=3)

z<-c(seq(from=6,to=12),rep(x=5.3,times=3),-3,seq(from=102,to=100,length.out=9))

length(z)

#2.3.3子集和元素的提取

myvec<-c(5,-2.3,4,4,4,6,8,10,40221,-8)

length(myvec)

myvec[1]

foo<-myvec[2]

foo

myvec[length(x=myvec)]

myvec.len<-length(x=myvec)

bar<-myvec[myvec.len-1]

ba

1:myvec.len

myvec[-1]

baz<-myvec[-2]

baz

qux<-myvec[-(myvec.len-1)]

qux

c(qux[-length(x=qux)],bar,qux[length(x=qux)])

length(x=qux)

qux[-length(x=qux)]

bar<-myvec[myvec.len-1]

ba

qux[length(x=qux)]

myvec[c(1,3,5)]

1:4

foo<-myvec[1:4]

foo

length(x=foo):2

foo[length(foo):2]

indexes<-c(4,rep(x=2,times=3),1,1,2,3:1)

indexes

foo[indexes]

bar<-c(3,2,4,4,1,2,4,1,0,0,5)

ba

bar[1]<-6

ba

bar[c(2,4,6)]<-c(-2,-0.5,-1) #用向量替换多个元素的值

ba

bar[7:10]<-100

ba

#练习

x<-seq(from=3,to=6,length.out=5)

x

y<-rep(x=c(2,-5.1,-33),times=2)

y

z<-7/42 2

z

x<-c(x,y,z)

x

x1<-x[c(1,5)]

x3<-x[-c(1,5)]

x4<-c(x1,x3)

sort(x=x,decreasing=FALSE)

x5<-sort(x=x,decreasing=FALSE)

x6<-x5[5:1] #使用冒号作为索引颠倒顺序

x6

x7<-c(rep(x=x3[4],times=3),rep(x=x3[6],times=4),rep(x=x3[10],times=1))

x7

x8<-sort(x=x,decreasing=FALSE)

x8[c(1,5:7,12)]<-c(99:95)

x8

0 人点赞