2017-07-27 159 views
1

我在R中有一個數據框用於閃亮的應用程序。這個數據框有一個最小值的列和一個最大值的列。然後得到的列是返回結果。它看起來像這樣:在最小和最大範圍表中查找值的位置

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

將通過用戶輸入接收數字。一旦給出了一個數字,就必須找到它所處的範圍。一旦找到相應的範圍,來自另一列的另一個數值必須從該範圍所在的同一行返回。如果某個條件爲真,則必須返回另一列的結果。例如,如果用戶將85作爲值,但條件測試爲false,則該函數應該返回45。

我一直沒有找到解決辦法。我已將ifbetween和增量for循環結合使用,但這不起作用(測試條件,然後找到between函數返回true的位置,然後匹配列並返回該值),並且我懷疑即使它確實工作,實現起來很慢,因爲這個功能將被集成到閃亮的應用程序的服務器端。有沒有一種方法可以實現這一點,並可能更有效?提前致謝。

回答

1

你在找什麼是功能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

0

你可以做這樣的事情:

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) 

所以它也適用於連續號碼。

我希望這有助於!

相關問題