如何使用 mutate() 创建一个值等于给定变量标签的变量?
How do I create a variable with mutate() that has values equal to the label of a given variable?
我正在尝试在我已经使用 gather()
的 data.frame
上使用 mutate()
来创建一个变量,其值为 label()
收集的 variable
。我搜索了 Google 和 Whosebug,但没有找到合适的答案。我的研究使我认为可能需要标准评估。
这是一个最小的可重现示例:
# 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
的标签。
我的目标是拥有类似的东西:
# 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
我正在尝试在我已经使用 gather()
的 data.frame
上使用 mutate()
来创建一个变量,其值为 label()
收集的 variable
。我搜索了 Google 和 Whosebug,但没有找到合适的答案。我的研究使我认为可能需要标准评估。
这是一个最小的可重现示例:
# 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
的标签。
我的目标是拥有类似的东西:
# 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