返回值基于df row和col

时间:2018-03-14 17:37:40

标签: r dataframe matrix

根据带约束的线性模型,我尝试根据最低值创建一个具有col#,行号和单元格值的df。 column是根据lm输出具有最低值的col。 row是具有最低值的相应行,现在我想要实际值并且我很难。如果你的好奇时间值是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)]会返回一个名为&#34; time&#34;来自a的值基于来自h的行和列,但是没有那么好用。我已经绞尽脑汁待了好几个小时,什么也没拿出来。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您必须循环遍历h行,然后使用aa中的行和列索引在h中提取值。

h$time <- apply( h, 1, function(x) aa[x[2], x[1]] )
h
#   column row  time
# 1      1   1  8262
# 2      1   2 21386
# 3      1   3 30698
# 4      2   4 53006
# 5      2   5 65205

数据:

aa <- structure(c(8262, 21386, 30698, 32711, 66156, 66357, 73307, 52547, 
53006, 65205), .Dim = c(5L, 2L))

h <- structure(list(column = c(1L, 1L, 1L, 2L, 2L), row = 1:5), .Names = c("column", 
"row"), row.names = c(NA, -5L), class = "data.frame")