How can I use the x as character in function(x)?

Hello, I am a newbie in all programming stuff. I feel like I have a super simple problem, but I cannot understand what's wrong. So, please excuse my insufficient knowledge.

This is my function:

best <- function(x) {
  x <- as.character(x)
  print(paste(x, "is the best"))
}
best(Eiffel65)

I thought that using as.character() function would be helpful. But I receive this error:

Error in best(Eiffel65) : object 'Eiffel65' not found

I can obtain the expected output by using quotes:

best("Eiffel65")
[1] "Eiffel65 is the best"

It is not a great big problem, but I just want to know.

Thanks in advance!

Hi,

Welcome to the RStudio community!

If you use a quoted piece of text, it is interpreted as a string, if it is unquoted though, R thinks it is a variable and this starts looking for a declared variable with that name and passes on its value to the function. Since Eiffel65 is not defined, R throws an error.

Here is a showcase when you do declare the variable Eiffel65 :

Eiffel65 = "other text"

best <- function(x) {
  x <- as.character(x)
  print(paste(x, "is the best"))
}

best(Eiffel65)
#> [1] "other text is the best"

Created on 2021-07-22 by the reprex package (v2.0.0)

Hope this helps,
PJ

1 Like

Hi,

May be you are looking for substitute instead of as.character

best <- function(x) {
  x <- substitute(x)
  print(paste(x, "is the best"))
}
best(Eiffel65)
1 Like

@pieterjanvc thank you very much! You opened up my horizon!

@gitdemont thank you as well! substitute() works very well!

Thanks to you both, I understand it way better than before!!! :slight_smile: :pray:

1 Like