变量在r中施加突变()函数后丢失标签
因此,假设我的一些DF列有标签。
library(Hmisc)
df1 <- data.frame(a = c(0,1,2), b = c(0,1,2), d = c(0,1,2), e = c(0,1,2),
f= c("m","f","o"), output = c(0,1,2))
var_labs <- c(a = "aaa",
b = "bbb",
#d = "ddd",
#e = "eee",
f = "fff",
output = "ooo")
label(df1) <- as.list(var_labs[match(names(df1), names(var_labs))])
当我应用mutate()
在任何列上函数时,该列会丢失其 标签。
library(dplyr)
df2 <- df1 %>%
mutate_if(is.character,
.funs = as.factor)
突变后有没有办法保留标签?
so assume some of my df columns have labels.
library(Hmisc)
df1 <- data.frame(a = c(0,1,2), b = c(0,1,2), d = c(0,1,2), e = c(0,1,2),
f= c("m","f","o"), output = c(0,1,2))
var_labs <- c(a = "aaa",
b = "bbb",
#d = "ddd",
#e = "eee",
f = "fff",
output = "ooo")
label(df1) <- as.list(var_labs[match(names(df1), names(var_labs))])
When I apply mutate()
functions on any column, that column loses its label.
library(dplyr)
df2 <- df1 %>%
mutate_if(is.character,
.funs = as.factor)
Is there a way to keep the labels after mutating?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
hmisc
标签功能函数授予数据中的各个向量。帧,而不是data.frame本身。因此,问题在于as.factor()
函数从列中删除了标签。您可以添加一个保留标签的版本,然后突变应保留这些标签,因为此新版本的
as.factor
将保留标签。The
Hmisc
labels functions annotate the individual vectors in the data.frame, not the data.frame itself. So the problem is that theas.factor()
function stips off the label from the column. You could add a version that preserves the labelsThen the mutate should keep those labels because this new version of
as.factor
will keep the labels.您可以首先保存
df1
的标签,然后再次将标签分配给匹配
in Columns todf2
像这样:输出:output:utput:
查看(df2)
:You could first save the labels of
df1
and after that assign again the labels tomatch
ing columns todf2
like this:Output:
view(df2)
: