r - In array, setting NAs in rows some data to 0 -


i've got array containing nas should in fact '0'.

  • i think of data 'rows' eg [1,,1] 1 row, [1,,2] another, [2,,1]
  • some such [a,,b] combinations should contain nas, , should remain are.
  • some 'rows' contain @ least 1 non-missing value. in this, case, nas in row should set zero.

example:

x <- c(rep(na,14),rep(na,4),20,30,40,rep(na,6),10,        rep(na,7),rep(na,4),20,30,40,rep(na,6),10,rep(na,7)) a1 <- array(x,dim=c(2,7,4)) a1[1,,]  [,1] [,2] [,3] [,4] [1,]   na   na   na   na [2,]   na   na   na   na [3,]   na   20   na   na [4,]   na   40   na   10 [5,]   na   na   na   na [6,]   na   na   na   na [7,]   na   na   30   na 

should

a1[1,,]  [,1] [,2] [,3] [,4] [1,]   na   na   na   na [2,]   na   na   na   na [3,]   0   20   0   0 [4,]   0   40   0   10 [5,]   na   na   na   na [6,]   na   na   na   na [7,]   0   0   30   0 

i've tried using function , apply() didn't anywhere

set0 <- function(x) { if (sum(is.na(x)) < length(x)) { x[is.na(x)] <- 0 } } 

you can do:

for (i in seq(dim(a1)[1])){     a1[i,,][array(!!rowsums(!is.na(a1[i,,])), dim(a1[i,,])) & is.na(a1[i,,])] <- 0 }  #> a1[1,,] #     [,1] [,2] [,3] [,4] #[1,]   na   na   na   na #[2,]   na   na   na   na #[3,]    0   20    0    0 #[4,]    0   40    0   10 #[5,]   na   na   na   na #[6,]   na   na   na   na #[7,]    0    0   30    0 #> a1[2,,] #     [,1] [,2] [,3] [,4] #[1,]   na   na   na   na #[2,]   na   na   na   na #[3,]    0   30    0    0 #[4,]   na   na   na   na #[5,]   na   na   na   na #[6,]    0    0   20    0 #[7,]    0   10   40    0 

explanation:

basically array(!!rowsums(!is.na(a1[i,,])), dim(a1[i,,])) boolean matrix lines numeric values have true elements. if operate first time penetrate loop (i=1, a1[1,,]), got:

#> array(!!rowsums(!is.na(a1[1,,])), dim(a1[1,,])) #      [,1]  [,2]  [,3]  [,4] #[1,] false false false false #[2,] false false false false #[3,]  true  true  true  true #[4,]  true  true  true  true #[5,] false false false false #[6,] false false false false #[7,]  true  true  true  true 

the boolean matrix array(!!rowsums(!is.na(a1[i,,])), dim(a1[i,,])) & is.na(a1[i,,]) takes - want - true values na values on row numerics.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -