r - 将列名作为参数传递给 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 的相对初学者,我真的很难理解它们。任何人都可以建议我需要的语法吗?
谢谢你。
解决方案
我们可以将输入的字符串转换为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")
推荐阅读
- javafx - JavaFX:也将鼠标事件传递给被遮挡的节点
- c - 计数连续的 1 位而不重叠
- java - JPA EntityGraph 在事务外抛出 LazyInitializationException
- curl - 无法获取 Github 组织存储库的问题
- sql - 如何将行转换为列 - 复杂的枢轴
- javascript - 如何命名一个新方法并让它通过一个函数?
- terraform - TFE cli 更新工作区时出错
- wordpress - 在 Wordpress 中,MySite.com/?p=795 通常会重定向到 MySite.com/Complete_URL/。目前它在我的网站上不起作用
- java - getAllCellInfo() 方法返回 null
- google-apps-script - 从 Google 应用制作工具中的其他项目访问项目