Search code examples
ruser-input

User inputs a function argument in r


I'm trying to accept as an argument of a function the user input but i have trouble making it work. My actual code is this:

t.student.2code <- function()
{
  f <- readline(prompt="Select column group A:")
  y <- readline(prompt="Select column group B:")


  t.test(f,y)



  }

Normal t.test

t.test(beaver1$time,beaver1$temp)

    Welch Two Sample t-test

data:  beaver1$time and beaver1$temp
t = 19.399, df = 113, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 1144.924 1405.387
sample estimates:
mean of x  mean of y 
1312.01754   36.86219 

Using beaver1$time and beaver1$temp as arguments in my function it doesn't work

Error in t.test.default(x, y) : not enough 'x' observations
Inoltre: Warning messages:
1: In mean.default(x) : argument is not numeric or logical: returning NA
2: In var(x) : si è prodotto un NA per coercizione

Solution

  • Your code looks okay. Note that readline() returns strings, so the function t.test must accept two string parameters.

    Simple example:

    testinp <- function() {
      c1 <- readline()
      c2 <- readline()
      sum(as.numeric(c1), as.numeric(c2))
    }
    

    In case you man t.test from the stats package, passing strings won't work as it expects numerical vectors. Maybe you want to specify variable names like the example below?

    c1 <- c(1,2,3)
    c2 <- c(2,4,5)
    testinp <- function() {
      tmp1 <- readline()
      tmp2 <- readline()
      t.test(get(tmp1), get(tmp2))
    }
    testinp() # enter "c1" and "c2"
    

    To handle the example your question:

    testinp <- function() {
      c1 <- readline()
      c2 <- readline()
      t.test(eval(parse(text=c1)), eval(parse(text=c2)))
    }
    testinp() # enter "beaver1$time" and "beaver1$temp"