我编写了一个带有2个参数的函数,但调用具有特定值的函数会引发错误消息。这是我的代码:
dynamicwilcox <- function(column, datacol) {
t = read.table("all.txt")
#print(column)
if(column=="Ph") {
uniphy=unique(c(t$Phylum))
print(uniphy)
}
if(column=="Cl") {
uniclass = unique(c(t$Class))
print(uniclass)
}
}
调用函数dynamicwilcox("Ph","A")
会给我一个错误。为什么呢?
答案 0 :(得分:1)
肯定会发生一些奇怪的事情 - 这是所有的错误信息吗?
如果我把你的代码带回基础并注释掉我无法运行的所有东西,因为我没有你的数据文件,下面的函数可以正常工作:
dynamicwilcox <- function(column,datacol) {
##dat <- read.table("all.txt") ## probably not good to call something t
if(column=="Ph") {
##uniphy=unique(c(t$Phylum))
##print(uniphy)
writeLines("column was 'Ph'")
}
if(column=="Cl") {
##uniclass = unique(c(t$Class))
##print(uniclass)
writeLines("column was 'Cl'")
}
}
R> dynamicwilcox("Ph", "A")
column was 'Ph'
也许您可以从上面的代码开始,看看它是否适合您,如果适用,请以此为基础。
对于dynamicwilcox(Ph, A)
工作,除非您已在当前环境中定义了对象Ph
和A
,否则它无法工作。它不会打印任何内容,因为 Ph
中存储的内容 等于"Ph"
或"Cl"
。如果你运行这两行,你会得到什么?:
R> Ph
R> A
希望这能解释为什么调用你的函数的方式失败了。
更新:至于更改使用readline()
的功能以便接受用户输入,这里有一个版本:
dynamicwilcox <- function() {
ANSWER <- readline("What column do you want to work on? ")
if(ANSWER=="Ph") {
writeLines("column was 'Ph'")
} else if(ANSWER=="Cl") {
writeLines("column was 'Cl'")
} else {
writeLines(paste("Sorry, we don't know what to do with column", ANSWER))
}
ANSWER ## return something
}
这里正在使用:
R> dynamicwilcox()
What column do you want to work on? Ph
column was 'Ph'
[1] "Ph"
R> dynamicwilcox()
What column do you want to work on? Cl
column was 'Cl'
[1] "Cl"
R> dynamicwilcox()
What column do you want to work on? FooBar
Sorry, we don't know what to do with column FooBar
[1] "FooBar"
但请阅读?readline
,因为在您可以学习的其中一个示例中,它有类似的内容。