function that iterates and assigns based on value in R

大憨熊 提交于 2019-12-02 08:23:57

问题


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

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.

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


回答1:


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


来源:https://stackoverflow.com/questions/41967792/function-that-iterates-and-assigns-based-on-value-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!