R語言之書2.3.3

  • 2019 年 12 月 31 日
  • 筆記

#章節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