Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding zeros in front of an vector

We are trying to put 730 zero values in front of an 365 X 1 vector with values. I cut out this vector from another matrix. Thus, the row index numbers are now no more helpful and confusing e.g. the vector with the values starts with 50. If I create another vector or array with the zero values and then use rbind to bind it before the vector with the values it will produce strange values due to mixed up row index numbers and handle it as a 3d element.

Thanks for any ideas how to achieve that or how to reset the row index numbers. best Fabian!

Example: This is my vector with values

 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
 ....

I want to add a zero vector with 730 rows in front of it. So it should look like this:

 1        0
 2        0
  ....
 731     -3.0538333   
 732     -2.8492875
 733     -3.1645825
  .... 
like image 538
Fabian Stolz Avatar asked Jun 20 '12 06:06

Fabian Stolz


3 Answers

Something like this?

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

Then you could make a matrix:

m <- cbind(1:length(a), a)
like image 194
johannes Avatar answered Sep 26 '22 01:09

johannes


You need to use the c() function to concatenate two vectors. To create a vector of zeroes, use rep():

Here is an example:

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
like image 25
Andrie Avatar answered Sep 25 '22 01:09

Andrie


Based on your example, it looks like your vector has class matrix. If that is a requirement, the following should work:

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
like image 38
BenBarnes Avatar answered Sep 25 '22 01:09

BenBarnes