下面是一個簡單的例子:編程分解數據框中的選定列,整潔的方式?
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