Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

r - 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.

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...