r - 在 R 中绘制多条 Bootstrap 曲线

标签 r

我想知道如何在 R 中绘制这些多条引导曲线。
我的代码就像

dat2 <- read.delim("bone.data", sep ="\t", header= TRUE)
y <- dat2[,4]
x <- dat2[,2]
plot(x,y,xlab="age",ylab="BMD",col=ifelse(dat2[,3]=="female","red","blue"))

多条Bootstrap Curves如图8.2左下图所示。
ESL

enter image description here

名为骨矿物质密度的数据可以从这个网站获得:
data

文件的直接链接是:here

最佳答案

您可以使用 smooth.spline 绘制样条曲线和 lines :

plot.spline = function(x, y, ...) {
    s = smooth.spline(x, y, cv=TRUE)
    lines(predict(s), ...)
}

所以要执行引导,按照书中的说明,你从数据中随机抽取行替换,然后调用 plot.spline在重新采样的数据上:
bootstrap.curves = function(dat, nboot, ...) {
    for (i in 1:nboot) {
        subdata = dat[sample(NROW(dat), replace=TRUE), ]
        plot.spline(subdata$age, subdata$spnbmd, ...)
    }
}

因此,您可以使用此函数为男性和女性运行单独的绘图:
bootstrap.curves(dat2[dat2$gender == "female", ], 10, col="red")
bootstrap.curves(dat2[dat2$gender == "male", ], 10, col="blue")

最终结果:

enter image description here

注意:此代码将产生许多警告(不是错误),如下所示:
1: In smooth.spline(x, y, cv = TRUE) :
  crossvalidation with non-unique 'x' values seems doubtful

这是因为自举重采样。 smooth.spline使用交叉验证来决定给出样条的自由度数,但它不希望重复 x 这样做。值(因为自举重采样总是有效的)。您可以通过选择自己的自由度数来解决这个问题,但这对于此目的来说可能没问题。

关于r - 在 R 中绘制多条 Bootstrap 曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244516/

相关文章:

r - 将制表符分隔的数据解析为 R data.table/data.frame 时如何排除某些行?

r - 数据表和扫描功能

python - 基于系列条件创建新的 pandas 列

r - ts(x) : 'ts' object must have one or more observations 错误

r - 用不同的变量值给每个面着色

R中的随机迭代循环

r - 指定应用 read_csv 的列数

r - 选择 dataTable 中的行以显示 Shiny 中另一个表中的数据

r - 从 xts 索引获取时间

r - R plot() 或 ggplot2() 中的对数 y 轴刻度线