我尝试获取每个向量的密度并计算y变量的标准偏差,但是那条线似乎与平均值不对应。
ln <- length(names(data))
hist(data_mean, breaks=100, prob=TRUE)
for( i in 1:ln ) {
lines(density(data[,i], na.rm = TRUE), col="grey", lwd=1)
}
dev.off()
答案 0 :(得分:1)
我认为以下代码可行。简而言之,我确定每个向量的密度,大约是一些已知的x值向量,将它们全部卡在矩阵中,然后计算摘要统计和绘图。这是你想要做的吗?
#Make up some fake data (each column is a sample)
mat=matrix(rnorm(5000,2,0.5),ncol=50)
#Determine density of each column
dens=apply(mat, 2, density)
#Interpolate the densities so they all have same x coords
approxDens=lapply(dens, approx, xout=seq(0.1,3.5,by=0.1))
#Create your output matrix, and fill it with values
approxDens2=matrix(0, ncol=ncol(mat), nrow=length(approxDens[[1]]$y))
for(i in 1:length(approxDens)){
approxDens2[,i]=approxDens[[i]]$y}
#Determine the mean and sd of density values given an x value
mn = rowMeans(approxDens2)
stdv = apply(approxDens2,1,sd)
#pull out those x values you approx-ed things by for plotting
xx = approxDens[[1]]$x
#plot it out
plot(xx, mn, las=1, ylim=c(0,1), type='l', ylab='Density', xlab='X')
lines(xx, mn+stdv, lty=2);lines(xx, mn-stdv, lty=2)
答案 1 :(得分:0)
我不完全确定你想要什么,但你能够保存密度的值。尝试
x <- rnorm(100)
dens <- density(x)
dens$y