r - Use of apply instead of loops for a matrix -
i have matrix (all_parameters) 150 columns , 100.000 rows. value each data element in matrix "1". replace values "0" if following conditions true:
col name either 10, 14, 27 row name starts "t1_"
i have following loop works fine:
t1_missing = c(10,14,27) for(i in 1:ncol(all_parameters)) { if (any(t1_missing == as.integer(colnames(all_parameters)[i]))) { for(j in 1:nrow(all_parameters)) { if(grepl("^t1_", rownames(all_parameters)[j])) { all_parameters[j,i] <- 0 } } } }
the problem execution of loops takes extraordinary long time. tried use apply function not able make work. can please show me how solved using apply function (or else superior , faster on for-loop).
thanks help!
would simple vectorized operation:
all_parameters[ grepl("^t1_", rownames(all_parameters) ), t1_missing] <- 0
further conditions on rows added either &
(which might make conditions more restrictive) or |
(to include more rows). assumed use of term "col names" meant refer these numeric position. using [ i, j]
-operations, can mix logical indices in i-rows numeric indices in j-columns. (now tested example jbaums: since deleted reproduced here:
m <- matrix(1, ncol=30, nrow=12, dimnames=list(paste0('t', rep(1:3, each=4), '_', rep(1:4, 3)), 1:30))
Comments
Post a Comment