首页 > 解决方案 > 将列名作为参数传递给 R 函数

问题描述

我有一段代码可以在 R 中生成一个图形。它可以工作,但是star_sign函数中有一个硬编码的字段名称。我想将其作为额外的函数参数传递variable_name并删除硬编码。

my_graph <- function (df_name, variable_name)
{
  scale_fac <- 4 * max(df_name$exposure) / max(df_name$max) # rule of thumb - it'll do for now

  row_count = nrow(df_name)

  #problem line here - star_sign appears twice

  df_name <- df_name %>% mutate(star_sign = as.numeric(factor(star_sign, levels = my_levels)))

  df_name %>%
    ggplot(aes_string(x = variable_name)) +
    geom_line(aes(y = mean), color = "red") +
    geom_line(aes(y = min), color = "blue") +
    geom_line(aes(y = max), color = "green") +
    geom_col(aes(y = exposure / scale_fac), width = 0.5, fill = "blue") +
    scale_y_continuous("Linear Predictor", sec.axis = sec_axis(~ .*scale_fac , name = "Exposure")) +
    scale_x_continuous(variable_name, breaks = c(1:row_count), labels = df_name$my_levels) +
    theme_bw()
}

df <- data.frame(star_sign = c("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"),
                 exposure = c(50, 70, 60, 40, 45, 78, 42, 22, 28, 49, 50, 31),
                 mean = c(1.1, 1.2, 1.4, 1.3, 1.8, 1.6, 1.4, 1.3, 1.2, 1.1, 1.5, 1.3))

df$min <- 0.95 * df$mean
df$max <- 1.05 * df$mean

df$my_levels = c("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces")

my_graph(df, "star_sign")

硬编码在这一行

  df_name <- df_name %>% mutate(star_sign = as.numeric(factor(star_sign, levels = my_levels)))

我已经阅读了各种关于将列名传递给 R 函数的 SO 文章,但我仍然是 R 的相对初学者,我真的很难理解它们。任何人都可以建议我需要的语法吗?

谢谢你。

标签: r

解决方案


我们可以将输入的字符串转换为symbol,然后进行求值 ( !!)

my_graph <- function (df_name, variable_name)
{
  scale_fac <- 4 * max(df_name$exposure) / max(df_name$max) # rule of thumb - it'll do for now

  row_count = nrow(df_name)

  #problem line here - star_sign appears twice

  df_name <- df_name %>% mutate(!! variable_name := as.numeric(factor(!! rlang::sym(variable_name), levels = my_levels)))

  df_name %>%
    ggplot(aes(x = !! rlang::sym(variable_name))) +
    geom_line(aes(y = mean), color = "red") +
    geom_line(aes(y = min), color = "blue") +
    geom_line(aes(y = max), color = "green") +
    geom_col(aes(y = exposure / scale_fac), width = 0.5, fill = "blue") +
    scale_y_continuous("Linear Predictor", sec.axis = sec_axis(~ .*scale_fac , name = "Exposure")) +
    scale_x_continuous(variable_name, breaks = c(1:row_count), 
             labels = df_name$my_levels) +
    theme_bw()
}

-检查

my_graph(df, "star_sign")

在此处输入图像描述


推荐阅读