基于R中的值进行迭代和赋值的函数
我想写一个函数,遍历一个帐户列表,每个帐户都有一个关联的值,并用一个名称列表中的一个名称分配该帐户。名称列表将有关联的值,我希望指定的名称是具有最小值的名称基于R中的值进行迭代和赋值的函数,r,loops,for-loop,while-loop,R,Loops,For Loop,While Loop,我想写一个函数,遍历一个帐户列表,每个帐户都有一个关联的值,并用一个名称列表中的一个名称分配该帐户。名称列表将有关联的值,我希望指定的名称是具有最小值的名称 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
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
我想要的是遍历accounts列表并查看names列表。首先查看acc1,将其指定给名称列表的min(totalvalue)。acc1的名称变为Jessica,Jessica的总值由acc1值增加。杰西卡27岁,然后acc2再次去找杰西卡,使杰西卡35岁,然后acc3找到现在是min的马特,并相应地分配它,等等
到目前为止,我所拥有的:
F <- function(listofnames, listofaccounts){
for (account in listofaccounts){
name <- min(listofnames$totalvalue)
listofaccounts$name <- name
}
F这不是很快,但应该可以:
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
myfunc谢谢!方向绝对正确。不过我还是不能让它工作。我使用的是dfs,而不是列表,我希望此输出能够更新dfs。在R中,从函数内部就地修改数据帧不是一种好的做法-如果您希望将它们作为输出,可以使用out重新分配。我想,我实际上不需要使用公式。我只是试着做一次,而不是多次重复这个公式。这应该只是一个for循环,但我仍然很难让它工作我让它工作!谢谢你的回答。既然我正在修改一个数据帧,那么放弃该函数并将其保持为一个简单的for循环是否更有意义?我没有重复这个,所以我不确定它是否需要一个公式。你知道我如何添加条件来分解所有内容吗。例如,假设我只想分配东北部的帐户,即acc3、acc4和acc7。(假设位置有另一列)。说杰夫和马特在东北部。在本例中,我尝试添加只在列表中查找“northeast”帐户的if语句,但得到了一个“theconditionhaselength>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