Reputation: 4060
I have dataframe
object in R:
dput(data_frame("n" = seq_len(10), "g" = sample(rep(factor(c("male", "female")), 5))))
structure(list(n = 1:10, g = structure(c(2L, 2L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L), .Label = c("female", "male"), class = "factor")), .Names = c("n",
"g"), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))
Now I want to add a 3rd column and put there g's level, where I want my levels to be 1:length(unique(g))
I am trying to do this using:
df %>% mutate(l = levels(g)))
Without luck, please advise what I am missing here?
Here is what I want:
n g l
1 male 1
2 female 2
3 male 1
4 female 2
5 male 1
..
Upvotes: 2
Views: 273
Reputation: 20095
There are couple of options:
# Store levels as list in new column
dataframe %>% mutate(l = list(levels(g)))
# Store levels as separate by ',' in new column
dataframe %>% mutate(l = paste(levels(g), collapse=","))
# Just a column with number
dataframe %>% mutate(l = as.integer(g))
# # A tibble: 10 x 3
# n g l
# <int> <fctr> <int>
# 1 1 male 2
# 2 2 male 2
# 3 3 female 1
# 4 4 female 1
# 5 5 female 1
# 6 6 female 1
# 7 7 female 1
# 8 8 male 2
# 9 9 male 2
# 10 10 male 2
Suggested by @DJV
#
df %>% mutate(l = paste(seq_along(levels(g)), collapse=","))
Upvotes: 3