· r-2

R: non-numeric argument to binary operator

When debugging R code, given my Java background, I often find myself trying to print out the state of variables along with an appropriate piece of text like this:


names = c(1,2,3,4,5,6)
> print("names: " + names)
Error in "names: " + names : non-numeric argument to binary operator

We might try this next:


> print("names: ", names)
[1] "names: "

which doesn't actually print the names variable - only the first argument to the print function is printed.

We'll find more success with the paste function:


> print(paste("names: ", names))
[1] "names:  1" "names:  2" "names:  3" "names:  4" "names:  5" "names:  6"

This is an improvement but it repeats the 'names:' prefix multiple times which isn't what we want. Introducing the toString function gets us over the line:


> print(paste("names: ", toString(names)))
[1] "names:  1, 2, 3, 4, 5, 6"
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket