R语言中最简单的向量赋值方法简介:
1. 生成等差数列的向量x
x <- 1:10 #将x向量赋值为1 2 3 4 5 6 7 8 9 10结果为
> x [1] 1 2 3 4 5 6 7 8 9 10
x[] <- 0 #非常简洁的赋值方法,建议使用 x[1:length(x)] <- 0 #不建议使用的赋值方法结果为:
> x[] <- 0 > x [1] 0 0 0 0 0 0 0 0 0 0
x <- seq(from = 1.5 , to = 8.2 ,by = 2.4)结果为:
> x [1] 1.5 3.9 6.3
4.使用rep函数
> w <- c("ab","123") > rep(w,2) [1] "ab" "123" "ab" "123" > rep(w,c(2,3)) [1] "ab" "ab" "123" "123" "123" >
5.修改向量维数
> x <- 1:8 > x [1] 1 2 3 4 5 6 7 8 > attr(x,"dim") <- c(2,4) > x [,1] [,2] [,3] [,4] [1,] 1 3 5 7 [2,] 2 4 6 8 > dim(x) <- c(4,2) > x [,1] [,2] [1,] 1 5 [2,] 2 6 [3,] 3 7 [4,] 4 8