繁体   English   中英

将列名作为参数传递给 R 函数

[英]Passing column name as parameter to R function

我有一段代码可以在 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 的相对初学者,我真的很难遵循它们。 任何人都可以建议我需要的语法吗?

谢谢你。

我们可以将字符串输入转换为sym BOL,然后做了评价( !!

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")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM