我需要一次标记多个变量。我想使用的基本方法是
iris<–iris
attr(iris$Sepal.Length, "label") <- "Sepal Length"
我想对所有变量进行迭代。有没有紧凑的方法可以做到这一点?
我创建了一个变量名称和标签列表
# First create my labels list.
lablist<-str_to_title(str_replace_all(names(iris), pattern = "\\.", replacement = " "))
# Second my variable names list
namelist<- names(iris)
但是,当我尝试迭代此方法时,我的方法失败了:我在做什么错?
# I attempt iteration
map2(namelist,lablist,~attr(iris[,.x], "label") <- .y)
理想情况下,我想将其map
用于迭代,但是如果它们更紧凑,更有效,我可以选择其他解决方案
非常感谢你的帮助
尝试这个
replace_labels <- function(df,new_labels){
column_names <- colnames(df)
purrr::map2(column_names, new_labels, ~ (df[[.x]] <-`attr<-`(df[[.x]], "label", .y)))
}
iris_labelled <- iris
lablist<-str_to_title(str_replace_all(names(iris), pattern = "\\.", replacement = " "))
iris_labelled[] <- replace_labels(iris_labelled,lablist)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句