我想使用变量(xdata)来定义使用vioplot函数显示的数据。试过以下方式,但不幸的是,它们不起作用。我怎样才能做到这一点?
library(vioplot)
x1 = mtcars$mpg[mtcars$cyl==4]
x2 = mtcars$mpg[mtcars$cyl==6]
x3 = mtcars$mpg[mtcars$cyl==8]
xdata = paste("x1","x2","x3",sep=",") # Try 1
xdata = c("x1","x2","x3") # Try 2
vioplot(xdata, names=c("4 cyl", "6 cyl", "8 cyl"),col="grey")
答案 0 :(得分:1)
如果您确实需要将数据作为变量传递,do.call
函数将以这样的方式执行操作:
library("vioplot")
x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]
xdata <- list(x1, x2, x3, names=c("4 cyl", "6 cyl", "8 cyl"), col="grey")
do.call(vioplot, xdata)
或者要绘制的变量是否作为character
?
编辑:为了更加动态地执行此操作,您可以使用以下内容:
cyls <- c(4, 6, 8)
cyldata <- lapply(cyls, function(cyl) mtcars$mpg[mtcars$cyl == cyl])
xdata <- c(cyldata, list(names=paste(cyls, "cyl"), col="grey"))
do.call(vioplot, xdata)
关键是你cyldata
等效的是list
。
答案 1 :(得分:0)
比这更容易!无需将x1,x2和x3粘贴/绑定/连接在一起。
vioplot(x1,x2,x3, names=c("4 cyl", "6 cyl", "8 cyl"),col="grey")
答案 2 :(得分:0)
我遇到了这个问题,试图弄清楚如何保存将传递给函数的参数的配置,并按需在另一行中传递它们。最初我并不清楚问题和答案,因此我为刚开始学习R的人提供了一个简单的演示。
例如,假设您有一个函数substr
,该函数带有参数x
,start
和stop
。
我们可以将参数保存到列表中并使用substr("Hello World", 2, 5)
来调用带有参数的函数,而不是调用"ello"
来获取do.call
:
params <- list("Hello World", 2, 5)
do.call(substr, params)
>> "ello"
如果只想保存start
和stop
,则可以在第一个参数前加上组合函数c
:
params <- list(2, 5)
do.call(substr, c("Hello World", params))
>> "ello"
您还可以使用在函数调用中指定参数的相同方法,将命名参数添加到列表中:
params <- list(stop=5, x="Hello World", start=2)
do.call(substr, params)
>> "ello"
并且列表可以混合命名和非命名参数:
params <- list("Hello World", start=2, stop=5)
do.call(substr, params)
>> "ello"
如果需要更复杂的逻辑,还可以将调用包装在工厂函数中:
make_substr <- function(start, stop){
return(
function(string) {
substr(string, start, stop)
}
)
}
substr_2_5 <- make_substr(2, 5)
substr_2_5("Hello World")
>> "ello"
substr_2_5("Goodbye")
>> "oodb"