假设我的矩阵M为1000x20。我想使用M的某些特定行向量形成一个新矩阵M'。假设v是以下行向量之一:
(sum(v[c(1,3,5)])<=m1) && (m2<= sum(v)) && (sum(v)<= m3)
m1,m2和m3是固定的实数值。
答案 0 :(得分:1)
您可以为此使用内置的rowSums
M[rowSums(M[,c(1,3,5)]) <= m1 & m2 <= rowSums(M) & rowSums(M) <= m3,]
答案 1 :(得分:0)
如果我很好理解,M'中的所有行都应满足这三个条件。
然后
M2 <- M[apply(M, 1, function(v) all(sum(v[c(1,3,5)]) <= m1, sum(v) >= m2, sum(v) <= m3)),]
示例:
set.seed(100)
m1 <- 1.5; m2 <- .1; m3 <- 7
M <- matrix(runif(1000 * 20), ncol = 20)
M2 <- M[apply(M, 1, function(v) all(sum(v[c(1,3,5)]) <= m1, sum(v) >= m2, sum(v) <= m3)),]
M2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 0.25767250 0.11186636 0.767613322 0.1170775 0.351589511 0.661712083 0.03935602 0.46841819 0.4721064346 0.172146627 0.01752519 0.08527665
[2,] 0.77030161 0.27888573 0.467701486 0.5135113 0.204069268 0.125491520 0.06858947 0.12662916 0.7292570788 0.285208830 0.05650994 0.14870733
[3,] 0.07242114 0.78926973 0.243863937 0.2129602 0.123911744 0.319162785 0.31567318 0.41284578 0.1001742624 0.667738556 0.27429634 0.22873886
[4,] 0.15563612 0.73555998 0.566519791 0.2586319 0.003557601 0.004678758 0.35639824 0.22556914 0.8001102153 0.191661312 0.39477327 0.28339573
[5,] 0.11080007 0.60440136 0.214702301 0.9420645 0.101179283 0.108814211 0.07295065 0.02647395 0.1982432718 0.280463005 0.29672992 0.03595338
[6,] 0.03995796 0.01779683 0.034120481 0.4319075 0.173509366 0.237607285 0.23590851 0.63668298 0.2373327424 0.306213750 0.47806018 0.10314514
[7,] 0.33464360 0.15353447 0.160568010 0.1304614 0.624373973 0.296702323 0.30006204 0.44803001 0.0004048729 0.279024218 0.58307526 0.25563003
[8,] 0.28269347 0.79171254 0.006763404 0.8829949 0.139567362 0.554091424 0.07773655 0.36361459 0.0417987099 0.003237072 0.29995648 0.47039652
[9,] 0.41103685 0.04635594 0.076752019 0.1238780 0.105824207 0.225368397 0.85102284 0.87449559 0.2695279971 0.213470059 0.18801495 0.49205221
[,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] 0.003809129 0.170773590 0.4111454 0.53899309 0.001633953 0.16027479 0.69589323 0.36884988
[2,] 0.398553511 0.796394822 0.1390867 0.39390073 0.124383915 0.07680161 0.40494816 0.21593826
[3,] 0.168761350 0.007325687 0.6380575 0.46103552 0.076197875 0.04746372 0.01994033 0.71738844
[4,] 0.888398457 0.969297715 0.3354494 0.03448252 0.227974761 0.18020713 0.12183392 0.04599925
[5,] 0.349111641 0.794708739 0.6964420 0.04796040 0.147109043 0.30419784 0.13573959 0.32682619
[6,] 0.227472877 0.404970699 0.6489886 0.30762523 0.945180172 0.45424866 0.29609562 0.45801963
[7,] 0.983473312 0.650270978 0.4376916 0.11810879 0.190460034 0.06142249 0.57051288 0.36678108
[8,] 0.114269206 0.163538058 0.1640480 0.39256770 0.607522648 0.09782059 0.17926967 0.91380213
[9,] 0.510501551 0.532380254 0.3818165 0.23163991 0.631005005 0.16757878 0.08121266 0.44285992