我试图接受用户输入作为函数的参数但我无法使其工作。我的实际代码是:
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
答案 0 :(得分:1)
您的代码看起来不错。请注意,readline()返回字符串,因此函数t.test必须接受两个字符串参数。
简单示例:
testinp <- function() {
c1 <- readline()
c2 <- readline()
sum(as.numeric(c1), as.numeric(c2))
}
如果您使用stats包中的man 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"
答案 1 :(得分:0)
# 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