r - Fill target array with dynamically shifted source array -


what way shift array number given per column?

i have following method filling full size array ("o") values of different array ("p", dimnames(p) exist in "o").

# empty target array  o <- array(dim=c(6,3),dimnames=list(c(1:6),c(1:3)))   # partially filled source array p <- array(c(10:16),dim=c(2,3),dimnames=list(c(2:3),c(1:3)))   > p    1  2  3 2 10 12 14 3 11 13 15  # fill target array p  o[(match(names(p[,1]),names(o[,1]))),(match(names(p[1,]),names(o[1,])))] <- p  > o     1  2  3  1 na na na  2 10 12 14  3 11 13 15  4 na na na  5 na na na  6 na na na  

now rewrite matching array call shift each column value in column header (only simplification picked 1:3).

in example, shift first column 1, 2nd column 2 , on).

the result this:

   1  2  3  1 na na na  2 na na na  3 10 na na  4 11 12 na  5 na 13 14  6 na na 15  

is there way solve without going manual looping?

i have tried in direction

o[(match(names(p[,1]),as.integer(names(o[,1]))-as.integer(names(o[1,])))),(match(names(p[1,]),names(o[1,])))] <- p 

and extract colnames, had go looping.

thanks

shift <- function(m) {   #find indices of non-nas   ind <- which(!is.na(m), arr.ind = true)   #create shifted indices   ind_shifted <- ind   ind_shifted[, "row"] <- ind_shifted[, "row"] +                               as.integer(colnames(m))[ind_shifted[, "col"]]   #fill matrix shifted values   m_shifted <- m + na   m_shifted[ind_shifted] <- m[ind]   m_shifted }  shift(o) #   1  2  3 #1 na na na #2 na na na #3 10 na na #4 11 12 na #5 na 13 14 #6 na na 15 

if use zeros instead of nas (i.e., 0 not valid value), more efficiently sparse matrices.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -