首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将反应性对象的值作为列添加到现有数据帧中

将反应性对象的值作为列添加到现有数据帧中
EN

Stack Overflow用户
提问于 2016-08-01 22:19:31
回答 1查看 1.9K关注 0票数 1

我刚开始使用闪亮的,并且在向现有数据帧中添加反应性值时遇到了一些问题。

我有一个名为CalculatedDistance的反应性对象,它用于计算当这个闪亮的应用程序上的输入发生变化时的距离。我试图将此对象中的计算出的距离添加到数据帧中的新列中,但收到以下错误消息:

Error in CalculatedDistance[i] : object of type 'closure' is not subsettable

下面的代码可以正常工作,直到我尝试将值添加到新列。

代码语言:javascript
运行
复制
library('shiny') #allows for the shiny app to be used

alldata <- iris

#adds a column of a unique ID for each row
alldata$ID <- 1:nrow(alldata)

# UI

ui<-fluidPage(
titlePanel("Explorer"),
fluidRow(
       wellPanel(
         numericInput(inputId = "UserPetalLength", label="Input Petal Length", value = 0, step = 0.1),
         numericInput(inputId = "UserPetalWidth", label="Input Petal Width", value = 0, step = 0.1)),
         tableOutput('Table')
))

#SERVER
server<-function(input,output,session)
{
 CalculatedDistance<- reactive({
    calculatedDistance <- sqrt((alldata$Petal.Length-input$UserPetalLength)^2 + (alldata$Petal.Width-input$UserPetalWidth)^2)
  })

 alldata$distance<- NA
 nRows <- nrow(alldata)
 for (i in 1:nRows)
 {
   alldata$distance[i]= CalculatedDistance[i]
 }
 output$Table = renderTable(alldata)

}


#Run the Shiny App to Display Webpage
shinyApp(ui=ui, server=server)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-01 23:04:09

这对我起了作用;我在server中做了一些修改以使其正常工作。

  • 在反应性环境中包装了添加到dataframe部件
  • 您所拥有的循环是不必要的,因为CalculatedDistance返回一个向量,我们可以很容易地将它添加到dataframe中
  • {}中添加了一对output$Table
  • 将dataframe转换为datatable
代码语言:javascript
运行
复制
    #server.R


    shinyServer(function(input,output,session)
    {
      CalculatedDistance<- reactive({
        calculatedDistance <- sqrt((alldata$Petal.Length-input$UserPetalLength)^2 + (alldata$Petal.Width-input$UserPetalWidth)^2)
        calculatedDistance
      })

      add_to_df <- reactive({
        alldata$distance<- NA
        nRows <- nrow(alldata)
        alldata$distance <- CalculatedDistance()

        alldata

      })

      output$Table <- renderTable({
        data.table(add_to_df())

      })

    })
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38708990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档