简体   繁体   中英

Problem with function arguments in R

I wrote a function that takes 2 parameters , but calling the function with specific values raises an error message. Here's my code:

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)
    }   
}

Calling the function dynamicwilcox("Ph","A") gives me an error. Why?

Something strange is certainly going on - was that all of the error message?

If I take your code back to basics and comment out all the stuff I can't run because I don't have your data file, the following function works without error:

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'

Perhaps you could start with the above code and see if it works for you, and if it does, build upon it.

As for dynamicwilcox(Ph, A) working, it can't work unless you have already defined objects Ph and A in your current environment. It won't print anything because whatever is stored in Ph is not equal to "Ph" or "Cl" . What do you get if you run these two lines ?:

R> Ph
R> A

Hopefully that will explain why that way of calling your function failed.

Update: As for altering the function to use readline() so it accepts user input, here is one version:

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
}

Here it is in use:

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"

But do read ?readline as it has something just like this in one of the examples that you could learn from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM