scs217
scs217

Reputation: 2378

RMarkdown V2 Shiny Document and dplyr

I'm trying to use an input selection for rmarkdown v2 with dplyr to select certain columns to be reported. The selected column will then be used in a formula given to the nls() function to determine the value of some constant C.

My code is as follows:

---
title: "Test"
author: "Author"
date: "Wednesday, June 18, 2014"
output: html_document
runtime: shiny
---

```{r, echo=TRUE}
require(dplyr)
#Some sample random data in a data.frame:
test=data.frame(A=runif(n=10),V=runif(n=10),N=runif(n=10))

#Input box to choose desired column
inputPanel(
  selectInput('sample.choice', label = 'Choose Columns',
              choices = c('V Sample'='V',
                          'N Sample'='N'),
              selected='N')
)

#Make a reactive data.frame to be used with the nls function
test2=reactive(test%.%select(A,input$sample.choice))

#Display the data.frame
renderDataTable(test2())

#Use nls solver to determine a constant with a given formula:
c.fit=reactive(nls(A ~ I(C*input$sample.choice),data=test2(),start=list(C=1)))
renderText(summary(c.fit()))
```

I get as output Error: non-numeric argument to mathematical function after the call to renderDataTable and to renderText.

Can anybody help me figure out what is wrong here?

Update

Based on @wch comments, I have fixed the dplyr select function. I was also trying to call renderText, but the output of summary.nls is of type list. This won't work, and I needed to run renderPrint instead. See below for working code:

```{r, echo=TRUE}
require(dplyr)
test=data.frame(A=runif(n=10),V=runif(n=10),N=runif(n=10))

inputPanel(
  selectInput('sample.choice', label = 'Choose Columns',
              choices = c('V Sample'='V',
                          'N Sample'='N'),
              selected='N')
)

renderText(input$sample.choice)

test2=reactive(test%.%select(A,matches(input$sample.choice)))

renderDataTable(test2())

renderPrint({
  data=test2()
  formula=paste0('A ~ I(C*',input$sample.choice,')')
  c.fit=nls(formula,data=data,start=list(C=1))
  summary(c.fit)
})

```

Upvotes: 1

Views: 918

Answers (1)

wch
wch

Reputation: 4117

I think the problem is that this line:

test %>% select(A, input$sample.choice)

ends up resolving to something like this:

test %>% select(A, "V")

But dplyr needs this because it uses non-standard evaluation:

test %>% select(A, V)

This is a possible workaround:

test %>% select(A, matches(input$sample.choice))

Upvotes: 5

Related Questions