Reputation: 2367
Please see Reprodex below. How to make it run? Is that possible with data.table or any other way?
---
title: "Interactive Filtering of 'mtcars'"
output: html_document
runtime: shiny
---
```{r}
library(shiny)
library(data.table)
dt <- data.table(mtcars)
textInput("filter", "Enter filter using R syntax:", "",
placeholder="(cyl==6) & (hp>100)")
h5("Works:")
renderTable({
dt[(cyl==6) & (hp>100)]
})
h5("Does not Work:")
renderTable({
q = quote("(cyl==6) & (hp>100)")
dt[eval(q)]
})
renderTable({
dt[eval(quote(input$filter))]
})
Upvotes: 1
Views: 27
Reputation: 341
Maybe this can help resolve your problem:
dt <- mtcars
f <- "(dt$cyl==6) & (dt$hp>100)"
dt[(dt$cyl==6) & (dt$hp>100), ]
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
# OR
dt[eval(parse(text = f)), ]
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
You should be able to use eval(parse(text = ...))
to wrap over your input$filter
!
Also, right now in your textInput
you only put a placeholder. I suggest you switch it to a default value using the value =
argument.
And so, this would work:
---
title: "Interactive Filtering of 'mtcars'"
output: html_document
runtime: shiny
---
```{r}
library(shiny)
library(data.table)
dt <- data.table(mtcars)
textInput("filter", "Enter filter using R syntax:", value="(cyl==6) & (hp>100)",
placeholder="(cyl==6) & (hp>100)", )
renderTable({
dt[eval(parse(text = input$filter))]
})
Upvotes: 2