Thursday, April 1, 2010

R Convert Numbers to String

For a recent R graph I needed to pull some numbers out of a database and later use those numbers as labels in the graph legend.

The legend method takes a "character or expression vector" NOT a vector of numbers much to my dismay. So I was left with a vector of numbers that I wanted to use as a legend and the legend method would not accept them. I was unable to find a method that converted this for me a`la java ( String.valueOf() ).

Here is how I did it:
#assume a vector of numbers already exists
numbers <- c(10,20,30,40)

#create a vector to hold text for legend
legend_text <- character()

#add the current numeric value to the legend text as a string
for number in numbers
{
  legend_text[length(legend_text)+1] = as.character(number)
}

#legend_text now contains a character vector and can be passed to the legend method

No comments:

Post a Comment