【问题标题】:Return value based on df row and col基于 df 行和列的返回值
【发布时间】: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 &lt;- aa[h$row,c(h$column)] 会根据 h 中的行和列返回一个名为“time”的新列,其值来自 aa,但效果并不好。我已经绞尽脑汁好几个小时了,却一无所获。有什么想法吗?

【问题讨论】:

    标签: r dataframe matrix


    【解决方案1】:

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

    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")
    

    【讨论】:

    • 这很好用!你介意解释一下这个功能吗?这对我来说没有意义。 function(x) aa[x[2], x[1]]谢谢!
    • 它是一个匿名函数,参数为x,并以h的行值传递。
    • 尝试在函数内部使用browser(),查看x的值
    • apply( h, 1, function(x) { browser(); aa[x[2], x[1]] }) 然后您将进入调试模式。在此处输入x 以查看其值。要进入下一个迭代,您可以输入n,然后输入
    猜你喜欢
    • 1970-01-01
    • 2022-08-17
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多