【问题标题】:How do I create a variable with mutate() that has values equal to the label of a given variable?如何使用 mutate() 创建一个变量,其值等于给定变量的标签?
【发布时间】:2016-11-02 21:18:04
【问题描述】:

我正在尝试在 data.frame 上使用 mutate(),我已使用 gather() 创建一个变量,其值为 label() 用于收集的 variable。我搜索了 Google 和 StackOverflow 并没有找到合适的答案。我的研究使我认为可能需要标准评估。

这是一个最小的可重现示例:

# 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

【问题讨论】:

    标签: r dplyr tidyr hmisc


    【解决方案1】:

    这个呢?

    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
    

    【讨论】:

    • 哇。非常感谢。 #facepalm
    猜你喜欢
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多