如何从非数据框格式的R输出中提取参数绘制直方图?
方法1:修改原有代码直接存储目标值(推荐)
你当前的代码仅用cat将结果打印到控制台,没有存储New Estimate对应的lambda1值,只需调整replicate块的返回值即可直接拿到所有估计值:
# 调整后的代码,直接返回每次迭代的New Estimate(lambda1) estimates <- replicate(1000, { y <- rpois(200, 1) lambda0 <- 1 # 原有打印逻辑可根据需求保留或删除 # if(TRUE) cat( sprintf("%15s %15s %15s %15s\n", "LogL", "Score", "Information", "New Estimate")) logL <- sum((-lambda0) + y*(log(lambda0))) score <- sum((y/lambda0)-1) information <- sum(y/(lambda0)^2) lambda1 <- lambda0 + score/information # 原有打印逻辑可根据需求保留或删除 # cat( sprintf("%15.4f %15.4f %15.4f %15.5f\n", logL, score, information, lambda1)) # 返回lambda1作为每次重复的结果 lambda1 }) # 直接绘制直方图 hist(estimates, main = "New Estimate分布直方图", xlab = "lambda估计值", col = "lightblue")
方法2:捕获现有控制台输出解析提取
如果你不想修改原有模拟代码,可以直接捕获控制台打印的输出,再从中提取New Estimate列的数值:
# 捕获所有控制台输出 raw_output <- capture.output({ x <- replicate(1000, { y <- rpois(200, 1) lambda0 <- 1 for(i in 1:1) { if( i == 1 ) cat( sprintf("%15s %15s %15s %15s\n", "LogL", "Score", "Information", "New Estimate")) logL <- sum((-lambda0) + y*(log(lambda0))) score <- sum((y/lambda0)-1) information <- sum(y/(lambda0)^2) lambda1 <- lambda0 + score/information cat( sprintf("%15.4f %15.4f %15.4f %15.5f\n", logL, score, information, lambda1)) lambda0 <- lambda1 } }) }) # 过滤掉表头行,提取每行第四列的数值 estimates <- as.numeric(sapply(raw_output[raw_output != raw_output[1]], function(line) { strsplit(trimws(line), "\\s+")[[1]][4] })) # 绘制直方图 hist(estimates, main = "New Estimate分布直方图", xlab = "lambda估计值", col = "lightblue")
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

