5

我们试图将 730 个零值放在一个 365 X 1 的向量前面。我从另一个矩阵中剪下这个向量。因此,行索引号现在不再有用和令人困惑,例如具有值的向量以 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
  .... 
4

3 回答 3

5

像这样的东西?

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

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

m <- cbind(1:length(a), a)
于 2012-06-20T07:19:15.570 回答
4

您需要使用该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
于 2012-06-20T07:20:48.260 回答
3

根据您的示例,您的向量似乎具有 class 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
于 2012-06-20T07:50:54.107 回答