[R] Colors column don't give correct color with plot()
Sarah Goslee
sarah.goslee at gmail.com
Fri Jul 24 20:33:04 CEST 2009
Not a bug, just another failure to understand what R is doing when it imports
data or to actually look at your data.
By default, R converts strings to factors during the import process, and as you
found that completely changes the results (converts them to numbers, and uses
those to specify colors).
> mydata <- read.table("blah.csv", header=FALSE, sep=" ")
> str(mydata)
'data.frame': 5 obs. of 3 variables:
$ V1: int 1 1 1 1 1
$ V2: int 1 2 3 4 5
$ V3: Factor w/ 3 levels "black","green",..: 1 2 2 1 3
Instead, you need:
> str(mydata)
'data.frame': 5 obs. of 3 variables:
$ V1: int 1 1 1 1 1
$ V2: int 1 2 3 4 5
$ V3: chr "black" "green" "green" "black" ...
The third column is now a string, and you are all set. You could also use
color numbers directly, instead of names, and avoid any import problem.
Sarah
On Fri, Jul 24, 2009 at 2:23 PM, Vivek Ayer<vivek.ayer at gmail.com> wrote:
> Hey guys,
>
> I'm having trouble getting the correct colors, when they are read from
> a csv file. Here's an example:
>
> 1 1 black
> 1 2 green
> 1 3 green
> 1 4 black
> 1 5 peachpuff
>
> Call it blah.csv. Then I ran:
>
> data <- read.csv("blah.csv",header=FALSE,sep="")
>
> and then to plot the data, I ran:
>
> plot(data[,1],data[,2],col=data[,3])
>
> But the output reports a vertical line with colors:
>
> black
> red
> red
> black
> green
>
> going up. Is this a bug in R? If so, could someone fix it?
>
> Thanks,
> Vivek
>
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list