我有以下数据框和功能:
structure(list(vnum1 = c(-0.853002701467605, -2.41044831451325,
1.22391941685926, 0.539011835935724,
-1.33616761309235, -1.33762097068431,
0.0391687995434752, -0.0396899713936502,
-1.34004495967791, 0.731212395958092),
vnum2 = c(-0.0140296461607895, 0.649714762844125,
-0.202655014660386, 1.90785563726907,
0.240191747220876, 0.0395243104031934,
-2.1689146110194, -0.198126356757339,
1.89172814288286, -0.484592561521101),
vint1 = c(7L, 4L, 7L, 3L, 10L, 10L, 7L, 8L, 2L, 3L),
vint2 = c(2L, 8L, 2L, 7L, 3L, 3L, 2L, 8L, 4L, 6L),
vfac1 = structure(c(3L, 1L, 2L, 4L, 1L, 1L, 2L, 2L, 1L, 2L),
.Label = c("1", "2", "3", "4"), class = "factor"),
vfac2 = structure(c(3L, 4L, 4L, 2L, 4L, 1L, 1L, 2L, 1L, 4L),
.Label = c("1", "2", "3", "4"), class = "factor"),
vch1 = structure(c(5L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 5L),
.Label = c("A", "B", "C", "D", "E"), class = "factor"),
vbin1 = structure(c(1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L),
.Label = c("a", "b"), class = "factor")),
.Names = c("vnum1", "vnum2", "vint1", "vint2", "vfac1", "vfac2", "vch1", "vbin1"),
row.names = c(NA, -10L), class = "data.frame")
>
grfour1 <- function(gdf, first, second, third, fourth){
ggplot(gdf, aes(first, second)) +
geom_point(position = position_jitter(width = 0.2, height = 0)) +
facet_grid(third~fourth)
}
在运行命令时,出现以下错误:
> grfour1(rndf, vint1, vint2,vch1,vint2)
Error in eval(expr, envir, enclos) : object 'second' not found
>
错误在哪里?感谢您的帮助。
这里有几个问题。首先,ggplot
将列名称解析为aes
不带引号的,因此当您执行时aes(first, second)
,ggplot2
实际上会查找名为的列"first"
,"second"
而是查找包含您解析的名称的变量。第二个问题是R不知道是什么vints
,他认为这是全局环境中的某个对象,因此,您需要告诉它这是一个使用"vint1"
我的解决方案是
grfour1 <- function(gdf, first, second, third, fourth){
gdf <- gdf[c(first, second, third, fourth)]
names(gdf) <- c("first", "second", "third", "fourth")
ggplot(gdf, aes(first, second)) +
geom_point(position = position_jitter(width = 0.2, height = 0)) +
facet_grid(third ~ fourth)
}
library(ggplot2)
grfour1(rndf, "vint1", "vint2", "vch1", "vint2")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句