[R] Expanding matrix

arun smartpink111 at yahoo.com
Thu Mar 20 19:47:50 CET 2014


Hi,You could do:

m1 <- as.matrix(read.table(text="3 0.9 1
5 0.5 0.7
7 0.1 0.3",sep="",header=FALSE)) 
dimnames(m1) <- NULL
d2 <- data.frame(V1=1:10)
d1 <- as.data.frame(m1)

library(zoo)
res <- na.locf(merge(d1,d2,all=TRUE))
res[is.na(res)] <- 1
 res
#or

vec1 <- 1:10
indx <- vec1[!vec1 %in% m1[,1]]
res2 <- rbind(m1, matrix(c(indx,rep(NA,2*length(indx))),ncol=3))
res2 <- na.locf(res2[order(res2[,1]),])
res2[is.na(res2)] <- 1
res2


res <- as.matrix(res)
 dimnames(res) <- NULL
 identical(res,res2)
#[1] TRUE


A.K.





Hello everyone, 

I was having a problem as follow: 

Suppose I have randomly generated 3 numbers from 1:10, say 3, 5 
and 7 with corresponding values from some data, the matrix is in form: 

3 0.9 1 
5 0.5 0.7 
7 0.1 0.3 

Now i want to expand the matrix with 10 rows in the form: 

1 1 1 
2 1 1 
3 0.9 1 
4 0.9 1 
5 0.5 0.7 
6 0.5 0.7 
7 0.1 0.3 
8 0.1 0.3 
9 0.1 0.3 
10 0.1 0.3 

Is there any R program to compute this? I know its simple to do 
so though excel but I need to do it like thousand times.. Thanks for 
helping!



More information about the R-help mailing list