Factorize a numeric variable with Greek expression in labels in R
Asked Answered
A

2

1

Suppose the following data frame, I want to factorized var, and label numbers to Greek letters, from 1 to alpha, 2 to beta, 3 to gamma. But the following code does not work.

var<-c(1,1,2,2,3,3)
df<-as.data.frame(var)
df$var<-factor(df$var, levels=c(1,2,3),
               labels=c("1"=expression(alpha),
                        "2"=expression(beta),
                        "3"=expression(gamma)))

Why the final data frame is not greek letters but just text expressions? Can anyone help me on this? Thanks a lot.

Audiology answered 14/1, 2014 at 20:5 Comment(0)
G
3

Does your locale support these characters? Does '\u03b1' print an alpha character? If not, you'll need to change your encoding. E.g.,

Sys.setlocale('LC_CTYPE', 'greek')

Then replace your calls to expression with the unicode strings for alpha, beta, etc.

df$var<-factor(df$var, levels=c(1,2,3),
               labels=c("1"='\u03b1',
                        "2"='\u03b2',
                        "3"='\u03b3'))

The way you're using expression is only valid for plots. Unless you really need to have Greek letters in your factor, I suggest using the words 'alpha', 'beta', etc. until it's time to plot.

Gash answered 14/1, 2014 at 20:30 Comment(1)
This is what I am looking for, and thx for the explanation of using "expression"~Audiology
C
0

df$var=factor(var,labels=c('alpha','beta','gamma'))

This produces a dataframe with the 1,2,3 transformed into alpha, beta, gamma. Hope this is what you were looking for

Colliery answered 14/1, 2014 at 20:15 Comment(2)
This gives the results what my original code did, but thx anyway.Audiology
sorry I misunderstood, glad you could get what you wantedColliery

© 2022 - 2024 — McMap. All rights reserved.