函数根据R中的值进行迭代和赋值 [英] function that iterates and assigns based on value in R

查看:161
本文介绍了函数根据R中的值进行迭代和赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking to write a function that iterates through a list of accounts each with a value associated, and assign that account with one of the names in a list of names. The list of names will have values associated and I would like the assigned name to be the one with the least value.

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的值增加了。杰西卡变成27,然后acc2再次去杰西卡做杰西卡35,acc3然后发现马特现在是最小,并相应地分配等等。

What I would like is to iterate through the accounts list and look at the names list. first look at acc1, assign it to the min(totalvalue) of the names list. the name for acc1 becomes Jessica, and the totalvalue of Jessica is augmented by the acc1 value. Jessica becomes 27, then acc2 goes to Jessica again making Jessica 35, acc3 then finds Matt who is now the min, and assigns it accordingly etc.

我到目前为止:
$ b $

what I have so far:

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

我知道这是由于许多原因。

I know this is way off for a number of reasons. I was thinking of doing a while loop as well..

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

请帮忙!谢谢你:)

please help! Thank you kindly :)

推荐答案

这不是超级快,但它应该工作:

This is not super fast, but it should work:

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

这篇关于函数根据R中的值进行迭代和赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆