【发布时间】:2021-11-04 11:23:26
【问题描述】:
我有一个数据集和随附的数据字典。我想使用数据字典来设置数据集的变量标签。我尝试使用显式的for loop,但它似乎很慢。有没有办法使用 tidyverse 的 map 家族来实现相同的目标?
library(tidyverse)
mydata <- tibble(
a_1 = c(20,22, 13,14,44),
a_2 = c(42, 13, 32, 31, 14),
b = c("male", "female", "male", "female", "male"),
c = c("Primary", "secondary", "Tertiary", "Primary", "Secondary")
)
dictionary <- tibble(
variable = c("a", "b", "c"),
label = c("Age", "Gender", "Education"),
type = c("mselect", "select", "select")
)
variables <- names(mydata)
for (var in variables){
vm <- unique(str_remove_all(var, "_.*")) # Take care of the variables with _
varlbl <- filter(dictionary, variable == vm) %>%
select(label) %>% pull
attr(mydata[[var]], "label") <- varlbl
}
#---- Map the variable labels using map
#
【问题讨论】: