下面是一个简单的例子:编程分解数据框中的选定列,整洁的方式?
library(tidyverse)
frame <- tribble(
~a, ~b, ~c,
1, 1, 2,
5, 4, 7,
2, 3, 4,
3, 1, 6
)
key <- tribble(
~col, ~name, ~type, ~labels,
1, "a", "f", c("one", "two", "three", "four", "five"),
2, "b", "f", c("uno", "dos", "tres", "cuatro"),
3, "c", "f", 1:7
)
是否有在frame
跨列编程清扫和应用的具体因素班的基础上,key
参数优雅的方式?预期的结果将是:
# A tibble: 4 x 3
a b c
<fctr> <fctr> <fctr>
1 one uno 2
2 five cuatro 7
3 two tres 4
4 three uno 6
我迄今使用purrr
的map2()
最好的解决方案,但与分配是IMO不是最优雅:
frame[key$col] <- map2(key$col, key$labels,
function(x, y) factor(frame[[x]], levels = 1:length(y), labels = y))
有没有人有一个更整洁解?请注意,我的原始数据框有数百个列,我需要对其中大部分的不同级别/标签进行重新分类,因此该过程必须实现自动化。
哈德利有一个'forcats'包,如果这听起来很有趣。 – lmo
谢谢,我看了一下,它是相当不错的 - 但它不直接提供功能,以我想要的方式操纵数据帧... – Krizbi