【问题标题】:function that iterates and assigns based on value in R根据 R 中的值进行迭代和分配的函数
【发布时间】:2017-01-31 21:28:05
【问题描述】:

我正在寻找编写一个函数,它遍历一个帐户列表,每个帐户都有一个关联的值,并为该帐户分配名称列表中的一个名称。名称列表将具有关联的值,我希望分配的名称是价值最小的名称。

name    totalvalue
Jeff    54
Christy 43
Matt    29
Jessica 19


accounts   value   name
acc1       8
acc2       7
acc3       7
acc4       7
acc5       6
acc6       6
acc7       5
acc8       3

我想要遍历帐户列表并查看名称列表。首先查看 acc1,将其分配给名称列表的 min(totalvalue)。 acc1 的名称变为 Jessica,并且 Jessica 的总值由 acc1 值增加。 Jessica 变成 27 岁,然后 acc2 再次去 Jessica 让 Jessica 35 岁,acc3 然后找到现在是 min 的 Matt,并相应地分配它等等。

到目前为止我所拥有的:

F <- function(listofnames, listofaccounts){
        for (account in listofaccounts){
            name <- min(listofnames$totalvalue)
            listofaccounts$name <- name
           }

我知道这有很多原因。我也在考虑做一个while循环..

F <- function(listofnames, listofaccounts){
        count <- 8
        while (count > 0){
           for (account in listofaccounts){
               name <- min(listofnames$totalvalue)
               listofaccounts$name <- name
               count <- count - 1 
           }
        }
     }

请帮忙!谢谢你:)

【问题讨论】:

    标签: r loops for-loop while-loop


    【解决方案1】:

    这不是超级快,但应该可以:

    myfunc <-function(names, vals){
      for(i in 1:nrow(vals)){ #for each row
        idx <- which.min(names$totalvalue) #we find the index of the current min
        names$totalvalue[idx] <- names$totalvalue[idx] + vals$value[i] #add to the current min the current number
        vals$names[i] <- as.character(names$name[idx]) #add to the name list, the name of the current min
      }
      return(list(names, vals)) #return a list of the two outputs
    }
    myfunc(x,y)
    
    [[1]]
         name totalvalue
    1    Jeff         54
    2 Christy         46
    3    Matt         47
    4 Jessica         47
    
    [[2]]
      accounts value   names
    1     acc1     8 Jessica
    2     acc2     7 Jessica
    3     acc3     7    Matt
    4     acc4     7 Jessica
    5     acc5     6    Matt
    6     acc6     6 Jessica
    7     acc7     5    Matt
    8     acc8     3 Christy
    

    【讨论】:

    • 谢谢!绝对是在正确的方向。我仍然无法让它工作。我正在使用 dfs 而不是列表,我希望这个输出能够更新 dfs。
    • 从函数内部修改数据帧在 R 中不是很好的做法 - 如果您希望它们作为输出,您可以使用 out &lt;-myfunc(x,y) names &lt;- out[[1]] vals &lt;- out[[2]] 重新分配
    • 我实际上不需要使用公式,我在想。我真的只是想这样做一次,而不是多次重复这个公式。这应该只是一个 for 循环,但我仍然无法让它工作
    • 我让它工作了!感谢您的回答。由于我正在修改数据框,因此放弃该函数并将其保留为简单的 for 循环是否更有意义?我没有重复这个,所以我不确定它是否需要一个公式。
    • 你知道我会如何添加条件来分解所有内容吗?例如,假设我只想分配东北的帐户,分别是 acc3、acc4 和 acc7。 (假设有另一列位置)。说杰夫和马特在东北。我尝试在此示例中添加仅在列表中查找“northeast”帐户的 if 语句,但得到“条件长度 > 1 并且仅使用第一个元素”错误
    猜你喜欢
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多