在最小和最大范围表中查找值的位置

在最小和最大范围表中查找值的位置

问题描述:

我在R中有一个数据框用于闪亮的应用程序。这个数据框有一个最小值的列和一个最大值的列。然后得到的列是返回结果。它看起来像这样:在最小和最大范围表中查找值的位置

Min Max Return ReturnifConditionTrue 
71 80  40   30 
81 90  45   35 
91 100 50   40 

将通过用户输入接收数字。一旦给出了一个数字,就必须找到它所处的范围。一旦找到相应的范围,来自另一列的另一个数值必须从该范围所在的同一行返回。如果某个条件为真,则必须返回另一列的结果。例如,如果用户将85作为值,但条件测试为false,则该函数应该返回45。

我一直没有找到解决办法。我已将ifbetween和增量for循环结合使用,但这不起作用(测试条件,然后找到between函数返回true的位置,然后匹配列并返回该值),并且我怀疑即使它确实工作,实现起来很慢,因为这个功能将被集成到闪亮的应用程序的服务器端。有没有一种方法可以实现这一点,并可能更有效?提前致谢。

你在找什么是功能which()。它返回满足特定条件的位置。然后,您可以使用if语句来选择从中提取值的列。

tb = data.frame(
    Min = c(71, 81, 91), 
    Max = c(80, 90, 100), 
    Return = c(40, 45, 50), 
    ReturnifConditionTrue = c(30, 35, 40) 
) 

x = 75 
condition = TRUE 

pos = which(x >= tb$Min & x <= tb$Max) 

if (condition) { 
    val = tb$ReturnifConditionTrue[pos] 
} else { 
    val = tb$Return[pos] 
} 
+0

谢谢你的回答 - 它运作良好。我试图将'if'语句和'pos'计算放入命名函数中,以便我可以将它们移动到另一个R文件中并稍后调用它们。我不断收到涉及“关闭”和“字符”转换的错误。 'as.function'也没有工作。你有什么建议吗? – Shan

你可以做这样的事情:

df <- read.table(text="Min Max Return ReturnifConditionTrue 
71 80  40   30 
81 90  45   35 
91 100 50   40",header=T) 

library(shiny) 

ui <- shinyUI(
    fluidPage(
numericInput("number","Number: ",min=71,max=100,value=85,step=1), 
selectInput("condition","Condition:", choices=c("TRUE","FALSE")), 
textOutput("text") 
) 
) 

server <- function(input, output, session) { 

    my_result <- reactive({ 
    our_row <- which(input$number>=df$Min & input$number<=df$Max) 
    if(input$condition=="TRUE") 
    { 
     return(df[our_row,"ReturnifConditionTrue"]) 
    } 
    else 
    { 
     return(df[our_row,"Return"]) 
    } 

    }) 

    output$text <- renderText({my_result() }) 

} 

shinyApp(ui,server) 

虽然你可能会考虑改变你的数据帧到:

df <- read.table(text="Min Max Return ReturnifConditionTrue 
71 80  40   30 
80 90  45   35 
90 100 50   40",header=T) 

,然后改变条件

 our_row <- which(input$number>df$Min & input$number<=df$Max) 

所以它也适用于连续号码。

我希望这有助于!