用户在 r 中输入一个函数参数

User inputs a function argument in r

我试图接受用户输入作为函数的参数,但我无法使其正常工作。我的实际代码是这样的:

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


  t.test(f,y)



  }

正常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 

在我的函数中使用 beaver1$time 和 beaver1$temp 作为参数不起作用

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

您的代码看起来没问题。注意 readline() returns 字符串,所以函数 t.test 必须接受两个字符串参数。

简单示例:

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

如果您从 stats 包中获取 t.test,则传递字符串将无法正常工作,因为它需要数值向量。也许您想像下面的示例那样指定变量名称?

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"

处理你的问题的例子:

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

f <- c(1,2,3)
g <- c(3,5,6)
df <- data.frame(f,g)

tfunc1 <- function() {
    print("Available column names:")
    print(names(df))
    col1 <- readline(prompt="Enter column 1 name:\n")[[1]]
    col2 <- readline(prompt="Enter column 2 name:\n")[[1]]

    t.test(df[[col1]], df[[col2]])
}

tfunc2 <- function(localdf) {
    print("Available column names:")
    print(names(localdf))
    col1 <- readline(prompt="Enter column 1 name:\n")[[1]]
    col2 <- readline(prompt="Enter column 2 name:\n")[[1]]

    t.test(localdf[[col1]], localdf[[col2]])
}

tfunc1()
[1] "Available column names:"
[1] "f" "g"
Enter column 1 name:
f
Enter column 2 name:
g

    Welch Two Sample t-test

data:  df[[col1]] and df[[col2]]
t = -2.5298, df = 3.4483, p-value = 0.07459
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -5.7875506  0.4542173
sample estimates:
mean of x mean of y 
 2.000000  4.666667 

tfunc2(df)
[1] "Available column names:"
[1] "f" "g"
Enter column 1 name:
g
Enter column 2 name:
f

    Welch Two Sample t-test

data:  localdf[[col1]] and localdf[[col2]]
t = 2.5298, df = 3.4483, p-value = 0.07459
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.4542173  5.7875506
sample estimates:
mean of x mean of y 
 4.666667  2.000000