gpt4 book ai didi

r - 允许使用 slider (或其他 GUI 元素)操作变量的 R 输出设备?

转载 作者:行者123 更新时间:2023-12-04 11:45:06 24 4
gpt4 key购买 nike

我想绘制数据并操纵图中使用的变量(此处:rangeMinrangeMax)。变量变化的后果应该在图中直接可见。

我想要 GUI 元素(例如 slider ),我可以使用它来更改 rangeMinrangeMax 的变量值并调用 rangePlot () 函数。

R 中是否有提供 GUI 元素的输出设备?

# generate example data
n <- 100
x <- 1:n
y <- x + (runif(n) * 25)

# rangeMin: value I'd like to manipulate using sliders
# rangeMax: value I'd like to manipulate using sliders
rangePlot <- function(x, y, rangeMin, rangeMax) {
plot(x, y)

# linear regression using datapoints a a certain range
plotrange <- c(rangeMin:rangeMax)

# linear model (y is mapped on x)
linReg = lm(formula = y[plotrange] ~ x[plotrange])
abline(linReg, col=2)

# highlight points used for liniar regression
points(x[plotrange], y[plotrange], col=2, pch=3)

# show slope and intercept in the plot
text(
x=min(x),
y=max(y),
paste0(
"intercept: ", linReg$coefficients[1],
"\nslope: ", linReg$coefficients[2]
),
adj=c(0, 1)
)
}

# manual call
rangePlot(x=x, y=y, rangeMin=1, rangeMax=n)
rangePlot(x=x, y=y, rangeMin=0.2*n, rangeMax=0.8*n)
rangePlot(x=x, y=y, rangeMin=50, rangeMax=60)
#

最佳答案

详细说明评论。 RStudio 的 manipulate 包使这些事情变得非常容易。该包在 RStudio 中工作。如果您想在没有 RStudio 的情况下使用相同的语法,gWidgets2 中有一个示例(不需要 gWidgetsManipulate):

require(tcltk); require(tkrplot)
require(gWidgets2) # require(devtools); install_github(c("gWidgets2", "gWidgets2tcltk"), "jverzani")
options(guiToolkit="tcltk")
source(system.file("examples", "manipulate.R", package="gWidgets2"))

w <- gwindow("Manipulate example", visible=FALSE)

manipulate({
y <- get(distribution)(size)
plot(density(y, bw=bandwidth/100, kernel=kernel))
points(y, rep(0, size))
},
##
distribution=picker("Normal"="rnorm", "Exponential"="rexp"),
kernel=picker("gaussian", "epanechnikov", "rectangular",
"triangular", "cosine"),
size=picker(5, 50, 100, 200, 300),
bandwidth=slider(0.05 * 100, 2.00 * 100, step=0.05 * 100, initial=1* 100), # integers needed
button=button("Refresh"),

container=w
)
visible(w) <- TRUE

无论是使用 RGtk2 还是 Qt 后端,GUI 看起来都更好,但它们通常更难安装。

关于r - 允许使用 slider (或其他 GUI 元素)操作变量的 R 输出设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15831560/

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