本文介绍了如何使用mutate()创建一个变量,该变量的值等于给定变量的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我已使用 gather()
的 data.frame
上使用 mutate()
来创建一个变量,该变量的值是所收集的变量
的 label()
.我已经搜索了Google和StackOverflow,但没有找到合适的答案.我的研究使我认为可能需要标准评估.
I am trying to use mutate()
on a data.frame
that I have used gather()
on to create a variable whose values are the label()
for the gathered variable
. I have searched Google and StackOverflow and have not found a suitable answer. My research led me to think that standard evaluation might be needed.
这是一个最小的可重现示例:
Here is a minimal reproducible example:
# Packages
library(dplyr)
library(Hmisc)
library(tidyr)
library(lazyeval)
df <- mtcars %>%
tbl_df() %>%
slice(1)
label(df$mpg) <- "Miles per gallon"
label(df$cyl) <- "Cylinders"
df %>%
select(mpg, cyl) %>%
gather(variable, value) %>%
mutate_(.dots = interp(~attr(df$x, "label"), x = variable))
此代码产生:
# A tibble: 2 × 3
variable value `attr(df$mpg, "label")`
<chr> <dbl> <chr>
1 mpg 21 Miles per gallon
2 cyl 6 Miles per gallon
这显然只是获得 mpg
的标签.
which is clearly only getting the label for mpg
.
我的目标是拥有类似的东西
My goal is to have something like:
# A tibble: 2 × 3
variable value `attr(df$variable, "label")`
<chr> <dbl> <chr>
1 mpg 21 Miles per gallon
2 cyl 6 Cylinders
推荐答案
这是什么?
df %>%
select(mpg, cyl) %>%
gather(variable, value) %>%
mutate(labels = label(df)[variable])
# A tibble: 2 × 3
variable value labels
<chr> <dbl> <chr>
1 mpg 21 Miles per gallon
2 cyl 6 Cylinders
这篇关于如何使用mutate()创建一个变量,该变量的值等于给定变量的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!