SteveS
SteveS

Reputation: 4050

Add level column to a dataframe with factor column

I have the following toy example of my df:

    structure(list(a = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("1", 
"2", "3"), class = "factor"), b = c("ku", "pu", "dd", "ka", "la", 
"gu", "kuku", "pupu", "d", "a", "su", "mo", "kui", "pue", "vwe", 
"rr", "wq", "q", "ppr", "tr", "qs", "cf")), .Names = c("a", "b"
), row.names = c(NA, -22L), class = c("tbl_df", "tbl", "data.frame"
))

I want to transform a to be factor object and to populate it's levels to an additional column (with level 1 corresponding to 1's, 2 to 2's etc.)

Please advise how can I add this additional factor level column?

The desired output should be:

a   b     a_lev
1   k      1
1   v      1
1   fs     1 
1   fdf    1
2   fe     2
3   ee     3
2   ere    2 
1   rre    1 
2   rerere 2 
3   rer    3
2   ere    2
1   fd     1
1   fd     1

Upvotes: 1

Views: 1872

Answers (1)

akrun
akrun

Reputation: 887851

We extract the levels of the column and then expand it by matching with the element

df$a_lev <- levels(df$a)[df$a]

The class will be character, So, it is easier to use as.character

df$a_lev <- as.character(df$a)

Upvotes: 2

Related Questions