基于 R 中的值进行迭代和分配的函数 [英] function that iterates and assigns based on value in R

查看:13
本文介绍了基于 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,赋值给names列表的min(totalvalue).acc1 的名称变为 Jessica,并且 Jessica 的 totalvalue 增加了 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.

到目前为止我所拥有的:

what I have so far:

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

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

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 
           }
        }
     }

请帮忙!谢谢你:)

推荐答案

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

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天全站免登陆