Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My R function doesn't seem to be using the arguments I give it

I have created an R function that doesn’t seem to be using the arguments that I give it. It runs but the result is not the one I should be getting given the parameters I pass to it. The code I have is as follows:

test_function <- function(text1, text2, number1) {
    if (length(text1) == length(text2)) {
        print("Equal")
    } else {
        print("Not equal")
    }
    operation <- length(text1) + number1
    print(paste("The result for the operation is: "), operation)
}

x <- "Hello"
y <- "World!"
z <- 10

test_function(x, y, z)

Does anyone know why the result I’m getting is the following?

[1] "Equal"
[1] "The result for the operation is: "

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use nchar() instead of length().

In addition, paste("The result for the operation is:", operation).

test_function <- function(text1, text2, number1) {
    if (nchar(text1) == nchar(text2)) {
        print("Equal")
    } else {
        print("Not equal")
    }
    operation <- nchar(text1) + number1
    print(paste("The result for the operation is:", operation))
}

x <- "Hello"
y <- "World!"
z <- 10

test_function(x, y, z)
#[1] "Not equal"
#[1] "The result for the operation is: 15"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading