Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (7.3k points)
edited by

I have a data frame with some numerical variables and some categorical factor variables. The order of levels for those factors is not the way I want them to be.

numbers <- 1:4

letters <- factor(c("a", "b", "c", "d"))

df <- data.frame(numbers, letters)

df

#   numbers letters

# 1       1       a

# 2       2       b

# 3       3       c

# 4       4       d

If I change the order of the levels, the letters no longer are with their corresponding numbers (my data is total nonsense from this point on).

levels(df$letters) <- c("d", "c", "b", "a")

df

#   numbers letters

# 1       1       d

# 2       2       c

# 3       3       b

# 4       4       a

I simply want to change the level order, so when plotting, the bars are shown in the desired order - which may differ from default alphabetical order.

1 Answer

0 votes
by
edited by

To define levels in a factor manually, you can use the levels argument of the factor function as follows:

numbers <- 1:4

letters <- factor(c("a", "b", "c", "d") ,levels = letters[4:1])

df <- data.frame(numbers, letters)

 str(df)

'data.frame': 4 obs. of  2 variables:

 $ numbers: int  1 2 3 4

 $ letters: Factor w/ 4 levels "d","c","b","a": 4 3 2 1

A factor with levels “b” ,”c” ,”a” ,”d” :

 numbers <- 1:4

 letters <- factor(c("a", "b", "c", "d") ,levels = letters[c(2,3,1,4)])

 df <- data.frame(numbers, letters)

 str(df)

'data.frame': 4 obs. of  2 variables:

 $ numbers: int  1 2 3 4

 $ letters: Factor w/ 4 levels "b","c","a","d": 3 1 2 4

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...