indexing input ID issue in shiny

I have 2 input values to execute t.test in my shiny application. But when i tried below code, the output is not displayed. Can anyone help me

output$renderprint <- renderPrint({
    t.test(paste0(as.numeric(input$num),"~" ,input$cat,data = input_data))    
}) 

input$num is character values and input$cat is character

Error I am getting . Not sure why? Can we not declare input$num and input$cat in t.test? Because when I code directly as t.test(as.numeric(var1) ~ var2, data = input_data), I get the results. But if declare as t.test(paste0(as.numeric(input$num),"~" ,input$cat,data = input_data)) , I will not get the output

Warning in mean.default(x) :
  argument is not numeric or logical: returning NA
Warning in var(x) : NAs introduced by coercion
Warning: Error in if: missing value where TRUE/FALSE needed

The t.test function does not accept a string as input. You can convert a string to a formula using eval and parse. Something like this.

t.test(formula = eval(parse(text = paste(input$num, "~", input$cat))), data = input_data)

Why don't you try it on the command line first before you try to put it into shiny.

input_data <- data.frame(x = runif(10), y = c(rep("A",5), rep("B",5)))
t.test(formula = eval(parse(text = paste("x", "~", "y"))), data = input_data)
#> 
#>  Welch Two Sample t-test
#> 
#> data:  x by y
#> t = -0.13194, df = 6.6478, p-value = 0.8989
#> alternative hypothesis: true difference in means is not equal to 0
#> 95 percent confidence interval:
#>  -0.5156001  0.4616560
#> sample estimates:
#> mean in group A mean in group B 
#>       0.5835968       0.6105688

Created on 2021-01-20 by the reprex package (v0.3.0)

1 Like

Yes, you look in the Help for that function and see what kind of inputs it expects.

You can do this in RStudio by typing ?funcname in the console (provided the appropriate package is loaded). For example

> ?t.test

Or you can do it in the Help pane by typing t.test in the search bar.

Or you can do it by putting the cursor in from of "t.test" in the editor pane and hitting F1.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

great. Thanks But in general is there any way to check if any function does not accept a string as input

as.formula also converts a string containing a formula into a formula object. It may be easier to use.

Cheers
Steen

2 Likes