【发布时间】:2018-03-14 17:37:40
【问题描述】:
我正在尝试根据具有约束的线性模型基于最小值创建一个具有列号、行号和单元格值的 df。 column 是根据 lm 输出具有最低值的 col。行是具有最低值的相应行,现在我想要实际值,我很难过。如果您好奇,时间值是以秒为单位的 gmapsdistance 输出。
我得到了什么
> h
column row time.1 time.2 time.3 time.4 time.5
1 1 1 8262 8262 8262 66357 66357
2 1 2 21386 21386 21386 73307 73307
3 1 3 30698 30698 30698 52547 52547
4 2 4 32711 32711 32711 53006 53006
5 2 5 66156 66156 66156 65205 65205
我想要的是一个“时间”列,其最短时间对应于 aa 中的列和行。
> h
column row time
1 1 1 8262
2 1 2 21386
3 1 3 30698
4 2 4 53006
5 2 5 65205
这是一个可重现的例子:
library(lpSolve)
aa <- matrix(c(8262, 21386, 30698, 32711, 66156, 66357, 73307, 52547, 53006, 65205),
nrow=5,
ncol=2)
aa
#Run aa through a Linear model with lower constraint of 2 and upper constraint of 8
gwide <- aa
k <- ncol(gwide)
n <- nrow(gwide)
dir <- "min"
objective.in <- c(gwide)
A <- t(rep(1, k)) %x% diag(n)
B <- diag(k) %x% t(rep(1, n))
const.mat <- rbind(A, B, B)
const.dir <- c(rep("==", n), rep(">=", k), rep("<=", k))
const.rhs <- c(rep(1, n), rep(2, k), rep(8, k))
res <- lp(dir, objective.in, const.mat, const.dir, const.rhs, all.bin = TRUE)
res
#create a matrix from LM
soln <- matrix(res$solution, n, k)
soln
column <- apply(soln, 1, which.max)
h <- as.data.frame(column)
h$row = 1:nrow(h)
h$time <- aa[h$row,c(h$column)] #this seems to be where the problem is
h
我认为h$time <- aa[h$row,c(h$column)] 会根据 h 中的行和列返回一个名为“time”的新列,其值来自 aa,但效果并不好。我已经绞尽脑汁好几个小时了,却一无所获。有什么想法吗?
【问题讨论】: