在具有三个输入的 R 函数中使用 ggplot:数据帧的文件名和数字数据的两个列变量
Use ggplot in an R function with three inputs: filename of dataframe, and two column variables of numeric data
我想创建一个 R 函数作为输入:
- 我选择的数据框
- 包含数字数据的数据框的两列
输出应该是一列变量相对于另一列变量的散点图,同时使用基本 R plot
函数和 ggplot
.
这是一个玩具数据框:
df <- data.frame("choco" = 1:5,
"tea" = c(2,4,5,8,10),
"coffee" = c(0.5,2,3,1.5,2.5),
"sugar" = 16:20)
这是我写的函数,它不起作用(也用 base R plot
试过,但不起作用 - 代码未显示)
test <- function(Data, ing1, ing2) {
ggplot(Data, aes(x = ing1, y = ing2)) +
geom_point()
}
test(Data = df, ing1 = "choco", ing2 = "tea")
作为上述功能的一部分,我想合并一个 'if..else' 语句来测试 ing1 和 ing2 输入是否有效,例如:
try(test("coffee", "mint"))
- 以上输入应提示一条消息 'one or both of the inputs is not valid'
我可以看到使用
%in%
可能是执行此操作的正确方法,但我不确定语法。
df <- data.frame(
"choco" = 1:5,
"tea" = c(2, 4, 5, 8, 10),
"coffee" = c(0.5, 2, 3, 1.5, 2.5),
"sugar" = 16:20
)
test <- function(Data, ing1, ing2) {
if (ing1 %in% names(Data) & ing2 %in% names(Data)) {
ggplot(Data, aes(x = Data[, ing1], y = Data[, ing2])) +
geom_point()
}
else {
print("Both ing1, and ing2 has to be columns of data frame")
}
}
test(Data = df, ing1 = "choco", ing2 = "sugar")
此致,
格雷戈里
我想创建一个 R 函数作为输入:
- 我选择的数据框
- 包含数字数据的数据框的两列
输出应该是一列变量相对于另一列变量的散点图,同时使用基本 R plot
函数和 ggplot
.
这是一个玩具数据框:
df <- data.frame("choco" = 1:5,
"tea" = c(2,4,5,8,10),
"coffee" = c(0.5,2,3,1.5,2.5),
"sugar" = 16:20)
这是我写的函数,它不起作用(也用 base R plot
试过,但不起作用 - 代码未显示)
test <- function(Data, ing1, ing2) {
ggplot(Data, aes(x = ing1, y = ing2)) +
geom_point()
}
test(Data = df, ing1 = "choco", ing2 = "tea")
作为上述功能的一部分,我想合并一个 'if..else' 语句来测试 ing1 和 ing2 输入是否有效,例如:
try(test("coffee", "mint"))
- 以上输入应提示一条消息 'one or both of the inputs is not valid'
我可以看到使用
%in%
可能是执行此操作的正确方法,但我不确定语法。
df <- data.frame(
"choco" = 1:5,
"tea" = c(2, 4, 5, 8, 10),
"coffee" = c(0.5, 2, 3, 1.5, 2.5),
"sugar" = 16:20
)
test <- function(Data, ing1, ing2) {
if (ing1 %in% names(Data) & ing2 %in% names(Data)) {
ggplot(Data, aes(x = Data[, ing1], y = Data[, ing2])) +
geom_point()
}
else {
print("Both ing1, and ing2 has to be columns of data frame")
}
}
test(Data = df, ing1 = "choco", ing2 = "sugar")
此致, 格雷戈里