【发布时间】:2020-08-06 15:02:13
【问题描述】:
我正在尝试在 R 中创建一个函数,该函数将接受两个名称(字符)和两个双精度数。然后它将输出一个 ggplot2 热图。这是数据:
> dput(df)
structure(list(`0` = c(0.0608, 0.0791, 0.0514, 0.0223, 0.0072,
0.0019, 4e-04, 1e-04, 0, 0, 0), `1` = c(0.0912, 0.1186, 0.0771,
0.0334, 0.0109, 0.0028, 6e-04, 1e-04, 0, 0, 0), `2` = c(0.0684,
0.0889, 0.0578, 0.025, 0.0081, 0.0021, 5e-04, 1e-04, 0, 0, 0),
`3` = c(0.0342, 0.0445, 0.0289, 0.0125, 0.0041, 0.0011, 2e-04,
0, 0, 0, 0), `4` = c(0.0128, 0.0167, 0.0108, 0.0047, 0.0015,
4e-04, 1e-04, 0, 0, 0, 0), `5` = c(0.0038, 0.005, 0.0033,
0.0014, 5e-04, 1e-04, 0, 0, 0, 0, 0), `6` = c(0.001, 0.0013,
8e-04, 4e-04, 1e-04, 0, 0, 0, 0, 0, 0), `7` = c(2e-04, 3e-04,
2e-04, 1e-04, 0, 0, 0, 0, 0, 0, 0), `8` = c(0, 1e-04, 0,
0, 0, 0, 0, 0, 0, 0, 0), `9` = c(0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0), `10+` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), class = "data.frame", row.names = c("0",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10+"))
现在,如果我对轴上的名称(homeScore 和 awayScore)进行硬编码,它可以工作:
df %>%
as_tibble(rownames = "awayScore") %>%
pivot_longer(cols = -awayScore, names_to = "homeScore", values_to = "probability") %>%
mutate_at(vars(awayScore, homeScore), ~forcats::fct_relevel(.x, "10+", after = 10)) %>%
ggplot() +
geom_tile(aes(x=awayScore, y=homeScore, fill = probability)) +
scale_fill_gradient2(low = "red", mid = "white", high = muted("blue"))+
theme(plot.margin = unit(c(2,2,2,2),"cm"))
这是结果:
但现在,我希望 homeScore 和 awayScore 成为函数中的变量。所以这是我的新函数,具有相同的df:
TestFunction<-function(home,away){
df %>%
as_tibble(rownames = away) %>%
pivot_longer(cols = -away, names_to = "home", values_to = "probability") %>%
mutate_at(vars(away, home), ~forcats::fct_relevel(.x, "10+", after = 10)) %>%
ggplot() +
geom_tile(aes(x=away, y=home, fill = probability)) +
scale_fill_gradient2(low = "red", mid = "white", high = muted("blue"))+
theme(plot.margin = unit(c(2,2,2,2),"cm"))
}
但这个情节不是预期的:
我必须怎样才能使任一轴上的 homeScore 和 awayScore 成为函数的变量?
【问题讨论】: