我有以下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"
))
我想将a
转换为因子对象,并将其级别填充到其他列中(级别1对应于1,2到2等)
请告知如何添加此附加因子水平列?
所需的输出应为:
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
答案 0 :(得分:2)
我们提取列的levels
,然后通过与元素匹配来展开
df$a_lev <- levels(df$a)[df$a]
class
将是character
,因此,使用as.character
会更容易
df$a_lev <- as.character(df$a)