有一个矩阵A,如:
"scripts": { "start": "nodemon --watch server/data/**/*.js --exec \"npm run update && ./node_modules/.bin/babel-node server/index.js\"", "update": "./node_modules/.bin/babel-node server/utils/updateSchema.js", "deploy": "npm run clean && cross-env NODE_ENV=production webpack --config webpack.config.js && npm run update && npm run build-server && cross-env NODE_ENV=production node ./build/index.js", "build-server": "cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./build", "lint": "eslint --ignore-path .gitignore client server", "heroku-postbuild": "cross-env NODE_ENV=production webpack --config webpack.config.js && cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./lib", "clean": "rm -rf build && mkdir build" }
我想计算所有行中两个相邻数字之间的最大值和最小值差值。 然后过滤以仅限制相邻数字min在4到7之间的行,并且max在6到12之间 输出应该不返回任何行。
对于以下矩阵:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 11 14 17 20 23 26
[2,] 12 15 18 21 24 27
[3,] 13 16 19 22 25 28
结果应该是第1行
答案 0 :(得分:3)
您可以按如下方式处理:
d <- abs(apply(m, 1, diff))
m[apply(d, 2, min) %in% 4:7 & apply(d, 2, max) %in% 6:12,]
给出:
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 21 15 22 13 23 17 [2,] 27 18 13 25 16 11
使用过的数据:
set.seed(2)
m <- matrix(sample(11:28, 54, TRUE), nrow = 9)
答案 1 :(得分:1)
这是一种矢量化方法
library(matrixStats)
m1 <- abs(m[,-ncol(m) ] - m[,-1])
m[rowMins(m1) %in% 4:7 & rowMaxs(m1) %in% 6:12,]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 21 15 22 13 23 17
#[2,] 27 18 13 25 16 11
set.seed(2)
m <- matrix(sample(11:28, 54, TRUE), nrow = 9)