2

I'm trying to create a factor variable, but with negative values behind the labels. Is this not allowed?

> foo <- sample( -10:-1, 20, replace=T)
> factor( foo, levels=-1:-10 )
 [1] -7  -10 -8  -9  -2  -2  -1  -5  -7  -6  -6  -9  -1  -1  -6 
[16] -2  -9  -1  -4  -1 
Levels: -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
> 
> foo2 <- factor( foo, levels=-1:-10, labels=letters[16:25] )
> foo2
 [1] v y w x q q p t v u u x p p u q x p s p
Levels: p q r s t u v w x y

Values are positive! why?

> as.numeric( foo2 )
 [1]  7 10  8  9  2  2  1  5  7  6  6  9  1  1  6  2  9  1  4  1

[why would I want this? I was creating a heatmap with geom_tile() and wanted the column labels at the top of chart instead of bottom ... the solution to move this seems surprisingly complicated: ggplot2: Adding secondary transformed x-axis on top of plot and I thought I might fool ggplot by giving negative values to put the chart in the IV quadrant but alas...]

Community
  • 1
  • 1
sai
  • 145
  • 1
  • 7

1 Answers1

2

You can set negative labels, but perhaps not levels:

j = factor("Jack", levels=c("Jack", "Jill", "tumbling", "after"), labels=c(-1,0,1,2))
print(j)
## [1] -1
## Levels: -1 0 1 2
levels(j)
## [1] "-1" "0"  "1"  "2" 
as.integer(levels(j)[as.integer(j)])
## [1] -1

However, you won't get your expected value when using as.integer() or as.numeric() in the normal manner:

as.numeric(j)
## [1] 1
as.integer(j)
## [1] 1
Steve Pitchers
  • 7,088
  • 5
  • 41
  • 41