通过变量编号在 aes 中寻址 x 和 y [英] Addressing x and y in aes by variable number

查看:22
本文介绍了通过变量编号在 aes 中寻址 x 和 y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用列号而不是名称来绘制带有寻址变量的散点图,即代替 ggplot(dat, aes(x=Var1, y=Var2)) 我需要类似 <代码>ggplot(dat, aes(x=dat[,1], y=dat[,2])).(我说某事"是因为后者不起作用).

这是我的代码:

showplot1<-function(indata, inx, iny){数据<-indata打印(nrow(dat));# 这只是为了表明对象 'dat' 已定义p <- ggplot(dat, aes(x=dat[,inx], y=dat[,iny]))p + geom_point(size=4, alpha = 0.5)}testdata<-data.frame(v1=rnorm(100), v2=rnorm(100), v3=rnorm(100), v4=rnorm(100), v5=rnorm(100))showplot1(indata=testdata, inx=2, iny=3)

<块引用>

# eval(expr, envir, enclos) 中的错误:找不到对象dat"

解决方案

使用来自 ggplot2 V3.0.0 的新功能对@Shadow 的回答的变体:

showplot <- function(indata, inx, iny){nms <- 名称(输入数据)x <- nms[inx]y <- nms[iny]p <- ggplot(indata, aes(x = !!ensym(x), y = !!ensym(y)))p + geom_point(size=4, alpha = 0.5)}testdata <- data.frame(v1=rnorm(100), v2=rnorm(100), v3=rnorm(100), v4=rnorm(100), v5=rnorm(100))名称(测试数据)<- c(a-b",c-d",e-f",g-h",i-j")显示图(输入数据=测试数据,输入X=2,输入=3)

ensym 从包含在变量中的字符串创建一个符号(所以我们首先必须在函数的开头创建这些变量),然后 !! 取消引用它,这意味着它会像您输入函数的原始名称一样工作.

!! 仅在旨在支持它的函数的上下文中工作,通常是 tidyverse 函数,否则它只是意味着不是"(类似于 as.logical)..

I need to draw a scatterplot with addressing variables by their column numbers instead of names, i.e. instead of ggplot(dat, aes(x=Var1, y=Var2)) I need something like ggplot(dat, aes(x=dat[,1], y=dat[,2])). (I say 'something' because the latter doesn't work).

Here is my code:

showplot1<-function(indata, inx, iny){
  dat<-indata
  print(nrow(dat)); # this is just to show that object 'dat' is defined
  p <- ggplot(dat, aes(x=dat[,inx], y=dat[,iny]))
  p + geom_point(size=4, alpha = 0.5)
}

testdata<-data.frame(v1=rnorm(100), v2=rnorm(100), v3=rnorm(100), v4=rnorm(100), v5=rnorm(100))
showplot1(indata=testdata, inx=2, iny=3)

# Error in eval(expr, envir, enclos) : object 'dat' not found

解决方案

A variation on @Shadow's answer using new features from ggplot2 V3.0.0 :

showplot <- function(indata, inx, iny){
  nms <- names(indata)
  x <- nms[inx]
  y <- nms[iny]
  p <- ggplot(indata, aes(x = !!ensym(x), y = !!ensym(y)))
  p + geom_point(size=4, alpha = 0.5)
}   

testdata <- data.frame(v1=rnorm(100), v2=rnorm(100), v3=rnorm(100), v4=rnorm(100), v5=rnorm(100))
names(testdata) <- c("a-b", "c-d", "e-f", "g-h", "i-j")
showplot(indata=testdata, inx=2, iny=3)

ensym creates a symbol from the string contained in a variable (so we first have to create those variables at the start of the function), then !! unquotes it, which means it will work as if you had fed the function raw names.

!! works only in the context of functions designed to support it, usually tidyverse functions, else it just means "not not" (similar to as.logical)..

这篇关于通过变量编号在 aes 中寻址 x 和 y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆