> ns <- rpois(10000, 1) > table(ns) > ns > 0 1 2 3 4 5 6 7 > 3652 3757 1831 580 145 26 8 1 > mean(ns) ##发生次数的平均值 > [1] 0.9924 > var(ns) ##发生次数的方差 > [1] 0.9760398 > cov(x,y) ##协方差 > cor(x,y) ##相关系数,取值范围[-1,1],表示变量间线性相关度,线性相关为1,不想关为0
# Creating a sequence from 6.6 to 12.6.
v <- 6.6:12.6
print(v)
>[1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6
# Create vector with elements from 5 to 9 incrementing by 0.4.
print(seq(5, 9, by = 0.4)) #序列运算符,带步长
# The logical and numeric values are converted to characters.
s <- c('apple','red',5,TRUE)# c函数,如果其中一个元素是字符,则非字符值被强制转换为字符类型。
print(s)
>[1] "apple" "red" "5" "TRUE"
2.访问向量元素
t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat")
u <- t[c(2,3,6)]
print(u)
>[1] "Mon" "Tue" "Fri"
# Accessing vector elements using negative indexing.
x <- t[c(-2,-5)] # 倒序
print(x)
>[1] "Sun" "Tue" "Wed" "Fri" "Sat"
3.向量运算
# Create two vectors.
v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11,0,8,1,2)
# Vector addition.
add.result <- v1+v2
print(add.result)
# Vector substraction.
sub.result <- v1-v2
print(sub.result)
# Vector multiplication.
multi.result <- v1*v2
print(multi.result)
# Vector division.
divi.result <- v1/v2
print(divi.result)
结果:
[1] 7 19 4 13 1 13
[1] -1 -3 4 -3 -1 9
[1] 12 88 0 40 0 22
[1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000
> x<-1:5 > is.numeric(x) #判断是否为数值型向量。其他向量转换为数值型向量: as.numeric() > [1] TRUE > is.character(x) #判断是否为字符、逻辑的函数: is.character()、is.logical(),转化为字符、逻辑的函数: as.character()、as.logical() > [1] FALSE > x[6]<-6 #增加一个元素为6 > x[8]<-8 #增加一个元素为8,第七个元素自动赋值为“NA”,表示缺失值 > x > [1] 1 2 3 4 5 6 NA 8 > x[is.na(x)==F] #删除向量中的缺失值。函数 is.na() 判断是否为缺失值。 > [1] 1 2 3 4 5 6 8 > length(x[is.na(x)==F]) #返回x中非缺失值的个数 > [1] 7 > x<-x[1:length(x)-1] #删除最后一个元素 > x > [1] 1 2 3 4 5 6 NA > x[7]<-7 #更改某个元素,如第三个元素改为8 > x > [1] 1 2 3 4 5 6 7
hist(x, main = "Normal DIstribution")
v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
[1] "A"
[1] "B"
[1] "C"
[1] "D"
x=exp(a)
y=sqrt(x)
`R
v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
[1] “A”
[1] “B”
[1] “C”
[1] “D”
### 六、其他
```R
x=exp(a)
y=sqrt(x)