数值型向量的运算
向量可以用于算术表达式中,操作是按照向量中的元素一个一个进行的.同一个表达式中的向量并不需要具有相同的长度, 如果它们的长度不同,表达式的结果是一个与表达式中最长向量有相同长度的向量, 表达式中较短的向量会根据它的长度被重复使用若干次(不一定是整数次),直到与长度最长的向量相匹配, 而常数将被不断重复 — 这一规则称为循环法则(recycling rule). 例如, 命令
> x <- c(10.4, 5.6, 3.1, 6.4, 21.7)
> y <- c(x,0,x)
> v <- 2*x + y + 1
产生一个长度为11的新向量v, 其中2 x被重复2.2次,y 被重复1次,常数1被重复11次. 为了方便使用,我们对向量的运算稍作细分:
1、向量与一个常数的加、减、乘、除为向量的每一个元素与此常数进行加、减、乘、除
2、向 量 的 乘 方( ˆ )与 开 方(sqrt)为 每 一 个 元 素 的 乘 方 与 开 方, 这 对像log, exp,sin, cos,tan 等普通的运算函数同样适用;
3、向 量 的 乘 方( ˆ )与 开 方(sqrt)为 每 一 个 元 素 的 乘 方 与 开 方, 这 对
像log, exp,sin, cos,tan 等普通的运算函数同样适用;
4、不同长度向量的加、减、乘、除遵从循环法则(recycling rule), 但要注意这种场合通常要求向量的长度为倍数关系, 否则会出现警告: “长向量并非是短向量的整数倍”.
下面举例说明
> 5+c(4,7,17)
[1] 9 12 22
> 5*c(4,7,17)
[1] 20 35 85
> c(-1,3,-17)+c(4,7,17)
[1] 3 10 0
> c(2,4,5)^2
[1] 4 16 25
> sqrt(c(2,4,25))
[1] 1.414214 2.000000 5.000000
> 1:2+1:4
[1] 2 4 4 6
> 1:4+1:7
[1] 2 4 6 8 6 8 10
Warning message:
长的目标对象长度不是短的目标对象长度的整倍数 in: 1:4 + 1:7








暂无数据