在向量前添加零

时间:2012-06-20 06:57:59

标签: arrays r vector row zero

我们试图在值为365 X 1的向量前面放置730个零值。 我从另一个矩阵中剪切出这个矢量。因此,行索引号现在不再有用且令人困惑,例如值的向量以50开头。 如果我创建另一个具有零值的向量或数组,然后使用rbind在带有值的向量之前绑定它,它将产生奇怪的值,因为混合了行索引号并将其作为3d元素处理。

感谢任何想法如何实现或如何重置行索引号。 最好的法比安!

实施例: 这是我的值为

的向量
 pred_mean_temp
 366     -3.0538333
 367     -2.8492875
 368     -3.1645825
 369     -3.5301074
 370     -1.2463058
 371     -1.7036682
 372     -2.0127239
 373     -2.9040319
 ....

我想添加一个零向量,前面有730行。 所以看起来应该是这样的:

 1        0
 2        0
  ....
 731     -3.0538333   
 732     -2.8492875
 733     -3.1645825
  .... 

3 个答案:

答案 0 :(得分:5)

这样的东西?

# create a vector
a <- rnorm(730)
# add the 0
a <- c(rep(0,730), a)

然后你可以制作一个矩阵:

m <- cbind(1:length(a), a)

答案 1 :(得分:3)

您需要使用c()函数来连接两个向量。要创建零向量,请使用rep()

以下是一个例子:

x <- rnorm(5)
x <- c(rep(0, 5), x)
x
 [1]  0.0000000  0.0000000  0.0000000  0.0000000  0.0000000  0.1149446  0.3839601 -0.5226029  0.2764657 -0.4225512

答案 2 :(得分:3)

根据您的示例,您的矢量看起来像是matrix类。如果这是一项要求,则以下内容应该有效:

set.seed(1)

# Create an example 2-column, 500-row matrix
xx<-matrix(rnorm(1000,-2),ncol=2,dimnames=list(1:500,
  c("pred_mean_temp","mean_temp")))

# Subset 365 rows from one column of the matrix, keeping the subset as a matrix
xxSub<-xx[50:(50+365-1),"pred_mean_temp",drop=FALSE]

xxSub[1:3,,drop=FALSE]
#    pred_mean_temp
# 50      -1.118892
# 51      -1.601894
# 52      -2.612026

# Create a matrix of zeroes and rbind them to the subset matrix
myMat<-rbind(matrix(rep(0,730)),xxSub)

# Change the first dimnames component (the row names) of the rbinded matrix
dimnames(myMat)[[1]]<-seq_len(nrow(myMat))

myMat[c(1:2,729:733),,drop=FALSE]
#     pred_mean_temp
# 1         0.000000
# 2         0.000000
# 729       0.000000
# 730       0.000000
# 731      -1.118892
# 732      -1.601894
# 733      -2.612026