[R] Discrete values in levelplot?

David Winsemius dwinsemius at comcast.net
Sat Mar 27 16:04:07 CET 2010


On Mar 26, 2010, at 11:08 AM, Filipe Cadete wrote:

> Dear all,
>
> I am trying represent a matrix of discrete values. At the moment I  
> am using levelplot from the lattice package, but it seems to only  
> work with numerical values. Is there an option in levelplot that  
> will allow me to assign a color to a discrete value, or another  
> package that will do the same?
>
> To clarify, with levelplot I can represent a matrix such as:
>     [,1] [,2] [,3] [,4]
> [1,] "1"  "1"  "1"  "1"
> [2,] "1"  "5"  "5"  "2"
> [3,] "1"  "3"  "3"  "3"
>
> Which when plotted will have colors assigned based on a continuous  
> scale of values (from 1 to 5 in this case).
>
> What I am looking for is a way to represent a matrix of the type:
>
>     [,1] [,2] [,3] [,4]
> [1,] "A"  "B"  "C"  "D"
> [2,] "A"  "E"  "D"  "A"
> [3,] "B"  "C"  "C"  "C"
>
> where each letter would have a specific color assigned to it.

This would be one way to convert letters to R color names:

cmtx <-matrix(sample(LETTERS[1:8], 25, TRUE), ncol=5)
Vswitch <-Vectorize(switch)
Vswitch(EXPR=cmtx, A="red", B="yellow", C="orange", D="brown",  
E="blue", F="green", G="pink", H="light red")

But that did not provide a clear path to success with either  
levelplot() or image():

 > image(1:5, 1:5, matrix(Vswitch(EXPR=cmtx, A=1, B=2, C=3, D=4, E=5,  
F=6, G=7, H=8), ncol=5)  )

# worked

 > cmtx
      [,1] [,2] [,3] [,4] [,5]
[1,] "E"  "H"  "C"  "F"  "G"
[2,] "D"  "F"  "H"  "B"  "F"
[3,] "B"  "B"  "G"  "C"  "H"
[4,] "H"  "H"  "B"  "D"  "C"
[5,] "E"  "F"  "G"  "A"  "B"

 > ??ascii
 > require(R.oo); charToInt(cmtx)
Loading required package: R.oo
Loading required package: R.methodsS3
R.methodsS3 v1.0.3 (2008-07-02) successfully loaded. See ?R.methodsS3  
for help.
R.oo v1.6.5 (2009-10-30) successfully loaded. See ?R.oo for help.
  [1] 69 68 66 72 69 72 70 66 72 70 67 72 71 66 71 70 66 67 68 65 71  
70 72 67 66
# wrong "scale" for colors in R
 >  charToInt(cmtx)-charToInt("A") +1   # avoid "zero colors"
  [1] 5 4 2 8 5 8 6 2 8 6 3 8 7 2 7 6 2 3 4 1 7 6 8 3 2

 >  image(matrix(charToInt(cmtx)-charToInt("A") +1, ncol=5)  )

Same result as above.

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list