简体   繁体   English

长 ifelse 语句的替代方案

[英]Alternative to long ifelse statements

Say I have three individuals and I know the payment they require to enter different amounts of land into a scheme.假设我有三个人,并且我知道他们将不同数量的土地输入计划所需的付款。 I want to know how much land each participant would enter into the scheme for a given payment rate.我想知道对于给定的支付率,每个参与者将进入该计划的土地数量。 I want them to enter the max amount they are willing for that payment rate.我希望他们输入他们愿意支付的最高金额。 Previously I did this with a long ifelse statement, but that will not run inside a loop, so I'm looking for an alternative.以前我用一个很长的 ifelse 语句来做这个,但它不会在循环中运行,所以我正在寻找一个替代方案。

In this example, I've excluded a load of areas so it just presents as if participants can enter 50, 49 or 1 unit(s) of area.在此示例中,我已排除大量区域,因此它仅显示参与者可以输入 50、49 或 1 个单位的区域。

paym_sh1a=200
paym_area_50 <- c(250, 150, 210)
paym_area_49 <- c(240, 130, 190)
paym_area_1 <- c(100, 20, 90)

 area_enrolled<- 
   ifelse(paym_area_50<paym_sh1a,50,ifelse(paym_area_49<paym_sh1a,49, 
 ifelse(paym_area_1<paym_sh1a,1,0)))

You could create a table of your values:您可以创建一个值表:

paym_area = rbind(paym_area_50, paym_area_49, paym_area_1)

And then use vectorised operations more effectively.然后更有效地使用矢量化操作。 In particular, since your thresholds are decreasing, you could compare the whole table to the sh1a value, and count how many rows are below it:特别是,由于您的阈值正在降低,您可以将整个表与sh1a值进行比较,并计算其下方有多少行:

(sums = colSums(paym_area < paym_sh1a))
# [1] 1 3 2

This vector can be used as an index into your results:此向量可用作结果的索引:

values = c(0, 50, 49, 1)
(result = values[sums + 1L])
# [1] 50  1 49

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM