gpt4 book ai didi

R 将变量列索引传递给 ggplot2

转载 作者:行者123 更新时间:2023-12-03 05:29:19 25 4
gpt4 key购买 nike

我正在尝试将列索引传递给 ggplot 作为我将重复使用的函数的一部分。像:

myplot <- function(df){
ggplot(df, aes(df[, 1], df[, 2])) + geom_point()
}

我将始终使用第一列作为我的 x 变量,第二列作为我的 y 变量,但列名称在数据集之间会发生变化。我已经搜索遍了..有什么想法吗?

编辑:

这是我使用的答案:

require(ggplot2)

myplot <- function(df){
ggplot(df, aes_string(colnames(df)[1], colnames(df)[2])) + geom_point()
}

最佳答案

您可以使用aes_string代替aes来传递字符串而不是使用对象,即:

myplot = function(df, x_string, y_string) {
ggplot(df, aes_string(x = x_string, y = y_string)) + geom_point()
}
myplot(df, "A", "B")
myplot(df, "B", "A")

关于R 将变量列索引传递给 ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15458526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com