高校数学の質問スレ(医者・東大卒専用) Part438 (991レス)
1-

815: 05/01(木)09:07 ID:L1qIlz9/(1/4) AAS
ディリクレ事前分布のパラメータαを階層化することで、より信頼性の高いベイズ推定が可能となる。
特にこの問題のように「実際に歪んでいる可能性がある」かつ「繰り返しが少ない」ケースでは、階層ベイズモデルはより適切な枠組みです。
816: 05/01(木)09:09 ID:L1qIlz9/(2/4) AAS
Stanで作ったらコンパイルに時間がかかる。簡単なモデルはJAGSの方がいい。離散変数も扱えるし。
# JAGS model
library(rjags)

# Prepare the data
outcome_data <- c(rep(1, 17), rep(2, 21), rep(3, 15), rep(4, 21), rep(5, 20), rep(6, 6))
N <- length(outcome_data)
data_jags <- list(outcome = outcome_data, N = N)

# Initial values (adjust as needed)
inits_jags <- list(
list(alpha = rep(1, 6), eta = 1),
list(alpha = runif(6, 0.1, 2), eta = 5)
)

# Compile the model
model_jags <- jags.model(
file = "hierarchical_dice_model.jag",
data = data_jags,
n.chains = 2,
n.adapt = 1000
)

# Sampling
samples_jags <- coda.samples(
model = model_jags,
variable.names = c("prob_simplex", "alpha", "eta"),
n.iter = 4000
)

# Summary of the results
cat("\nJAGS Sampling Results Summary:\n")
summary(samples_jags)

# Extract posterior samples (prob_simplex)
prob_simplex_posterior_jags <- as.matrix(samples_jags[, grep("prob_simplex", varnames(samples_jags))])
head(prob_simplex_posterior_jags)

# Plotting (example: posterior distribution of probabilities for each outcome)
cat("\nPosterior Distribution Plots for Each Outcome:\n")
par(mfrow = c(2, 3))
for (i in 1:6) {
plot(prob_simplex_posterior_jags[, i], type = "l", main = paste("Prob[", i, "]"), xlab = "Iteration", ylab = "Probability")
abline(h = 1/6, col = "red", lty = 2)
}

dice_prob_mean=prob_simplex_posterior_jags
colors <- c("skyblue", "lightcoral", "lightgreen", "gold", "lightsalmon", "lightcyan")
for (i in 1:ncol(dice_prob_mean)) {
BEST::plotPost(dice_prob_mean[, i],
compVal=1/6,
xlab=paste("pip ", i),
xlim=c(0, 0.4),
main="",
col=colors[i],
border="black")
}
817: 05/01(木)09:14 ID:L1qIlz9/(3/4) AAS
事後分布が出せたのであとはオッズ比などの計算も容易。
画像リンク

818: 05/01(木)11:18 ID:L1qIlz9/(4/4) AAS
ニッチな値の探索処理が終了しないコード

rm(list=ls())
library(fmsb)
library(parallel)

alpha <- 0.05

# Function to perform a single simulation
sim_single <- function(N = 100) {
A <- sample(1:N, 1)
while (A > N - 2) A <- sample(1:N, 1)
B <- sample(N - A - 1, 1)
C <- N - A - B
ABC <- c(A, B, C)
abc <- sapply(ABC, function(x) sample(x, 1))
x <- abc
n <- ABC
m <- rbind(s = x, f = n - x)

bonf_res <- pairwise.fisher.test(x, n, p.adj = 'bonf')
holm_res <- pairwise.fisher.test(x, n, p.adj = 'holm')
fdr_res <- pairwise.fisher.test(x, n, p.adj = 'fdr')
none_res <- pairwise.fisher.test(x, n, p.adj = 'none')

bonf <- min(bonf_res$p.value, na.rm = TRUE)
holm <- min(holm_res$p.value, na.rm = TRUE)
fdr <- min(fdr_res$p.value, na.rm = TRUE)
none <- min(none_res$p.value, na.rm = TRUE)

list(m = m, bonf = bonf, holm = holm, fdr = fdr, none = none)
}

# Function to find a result that meets the criteria using parallel processing
find_result_parallel_loop <- function(alpha = 0.05, num_cores = detectCores() - 1) {
# Create a cluster of worker processes
cl <- makeCluster(num_cores)
# Ensure the cluster is stopped when the function exits
on.exit(stopCluster(cl))

# Export the sim_single function to the worker processes
clusterExport(cl, "sim_single")

# Load the fmsb library in the worker processes
clusterEvalQ(cl, library(fmsb))

cat("Searching for a result that meets the criteria...\n")

while (TRUE) {
# Run simulations in parallel
results <- parLapply(cl, 1:num_cores, function(i) { # Run as many simulations as cores
sim_single()
})

# Check the results for the desired condition
for (res in results) {
if (res$bonf > alpha && res$holm < alpha) {
cat("Result meeting the criteria found:\n")
return(res)
}
}
# If no result found in this batch, continue the loop
}
}

# Find the result using parallel processing until found
res_parallel_loop <- find_result_parallel_loop(alpha = alpha)

# Output the result (will be printed within the loop when found)
print(res_parallel_loop)
819: 05/01(木)19:36 ID:VtjTJL9d(1) AAS
3群以上の多群の比の比較検定で、ペアワイズでの有意差検定を行いボンフェローニ補正ではどのペアでも有意差なしだが、
ホルム補正では有意差がでるペアが存在するというデータを有意水準0.05として作成してください。
各群のサンプルサイズは不均等でもかまいません。
820: 05/01(木)19:38 ID:twZ5uJsW(1) AAS
質問スレなので宿題依頼スレでやってください
821: 05/01(木)22:05 ID:xi2mMyC+(1) AAS
またゴミがなんかいってるよ。アホなサイト引っ張りだしてきてでたらめほざいて。正しいこと言ってるサイトと見分けつかんのかね?大学院とかついてたらそれだけで信じるカス。書いてる内容メタくそやん。
822: 05/02(金)10:48 ID:+8QO9mMm(1/2) AAS
set.seed(123)
library(fmsb)

alpha <- 0.05
N <- 1000

sim <- function() {
# 群ごとのサンプルサイズ(不均等で可)
n1 <- sample(250:350, 1) # 低用量
n2 <- sample(250:350, 1) # 高用量
n3 <- N - n1 - n2 # プラセボ

# 各群の成功率設定(ペアでは差なし、プラセボ vs 合算で差あり)
p1 <- 0.30 # 低用量
p2 <- 0.31 # 高用量
p3 <- 0.22 # プラセボ(低め)

x1 <- rbinom(1, n1, p1)
x2 <- rbinom(1, n2, p2)
x3 <- rbinom(1, n3, p3)

m <- rbind(success = c(x1, x2, x3), failure = c(n1 - x1, n2 - x2, n3 - x3))

bonf_p <- suppressWarnings(min(as.vector(pairwise.fisher.test(m[1,], colSums(m), p.adj="bonf")$p.value), na.rm=TRUE))

combined <- matrix(c(x1 + x2, n1 + n2 - x1 - x2, x3, n3 - x3), nrow=2)
comb_p <- fisher.test(combined)$p.value

list(m = m, bonf = bonf_p, combined_p = comb_p, sizes = c(n1, n2, n3))
}

# 条件を満たすデータが出るまでループ
res <- sim()
while (!(res$bonf > alpha && res$combined_p < alpha)) {
res <- sim()
}

# 結果出力
res$m
cat("Bonferroni-adjusted pairwise p-value (min):", res$bonf, "\n")
cat("Combined treatment vs placebo p-value:", res$combined_p, "\n")
cat("Sample sizes:", res$sizes, "\n")
823: 05/02(金)11:02 ID:+8QO9mMm(2/2) AAS
set.seed(123)
library(fmsb)

alpha <- 0.05
N <- 1000

# Simulation function
sim <- function() {
# Random group sizes
n1 <- sample(250:350, 1) # Low-dose
n2 <- sample(250:350, 1) # High-dose
n3 <- N - n1 - n2 # Placebo
if (n3 < 100) return(NULL) # Skip too-small placebo

# Success rates from uniform distribution
p1 <- runif(1)
p2 <- runif(1)
p3 <- runif(1)

# Binomial draws
x1 <- rbinom(1, n1, p1)
x2 <- rbinom(1, n2, p2)
x3 <- rbinom(1, n3, p3)

# 3-group matrix
m3 <- rbind(success = c(x1, x2, x3),
failure = c(n1 - x1, n2 - x2, n3 - x3))
colnames(m3) <- c("Low", "High", "Placebo")

# Add 4th group = combined (low + high)
x4 <- x1 + x2
n4 <- n1 + n2
m4 <- cbind(m3, Combined = c(x4, n4 - x4))

# Perform pairwise Fisher's exact tests across 4 groups
pw <- suppressWarnings(pairwise.fisher.test(m4[1,], colSums(m4), p.adj="bonf")$p.value)
pw_vals <- as.vector(pw)
pw_vals <- pw_vals[!is.na(pw_vals)]
names_all <- names(pw_vals)

# Identify significant pairs
sig_idx <- which(pw_vals < alpha)
sig_names <- names(pw_vals)[sig_idx]

# Check if only Combined vs Placebo is significant
is_valid <- length(sig_idx) == 1 &&
any(grepl("Placebo-Combined|Combined-Placebo", sig_names))

if (is_valid) {
return(list(m = m4, probs = c(p1, p2, p3), sizes = c(n1, n2, n3), pvals = pw))
} else {
return(NULL)
}
}

# Run until condition met
res <- NULL
while (is.null(res)) {
res <- sim()
}

# Output results
print(res$m)
cat("Success probabilities (Low, High, Placebo):", round(res$probs, 3), "\n")
cat("Sample sizes (Low, High, Placebo):", res$sizes, "\n")
cat("Pairwise Bonferroni-adjusted p-values:\n")
print(res$pvals)
824: 05/02(金)22:44 ID:056ygUN9(1) AAS
EMPAREG試験の解析をベイズでやっていたら、低用量高用量を統合する必要もなかったはず。
頻度主義統計で有意差がでない237:253の範囲でもプラセボよりイベント発生を抑制することが示せる。

############## 237:253 ################

# JAGSモデル文字列
model_string <- "
model {
for (i in 1:N) {
s[i] ~ dbin(theta[i], n[i]) # n[i] を別に与える
theta[i] ~ dbeta(1, 1) # 非情報的事前分布
}
}
"

EMPA_REG=\(x,verbose=FALSE){
# データ
data_list <- list(
s = c(288, x, 490-x),
n = c(2333, 2345, 2342),
N = 3
)

# 初期値
# init_fun <- function() list(theta = runif(3, 0.05, 0.15))
init_fun <- function() list(theta = runif(3))

# モデル構築・初期化・実行
library(rjags)
model <- jags.model(textConnection(model_string),
data = data_list,
inits = init_fun,
n.chains = 3,
n.adapt = 1000)

# バーンインとサンプル取得
update(model, 1000)
samples <- coda.samples(model,
variable.names = c("theta"),
n.iter = 5000)
ms=as.matrix(samples)
Placebo=ms[,1]
Low=ms[,2]
High=ms[,3]
if(verbose){
ylim=c(0,max(max(density(Placebo)$y), max(density(Low)$y), max(density(High)$y)))
xu=max(max(density(Placebo)$x), max(density(Low)$x), max(density(High)$x))
xl=min(min(density(Placebo)$x), min(density(Low)$x), min(density(High)$x))
xlim=c(xl,xu)
plot(density(Placebo),xlim=xlim,ylim=ylim,xlab=quote(theta),ylab='',main='',col=8)
lines(density(Low),col='pink',lwd=2)
lines(density(High),col='red',lwd=2)
}
c(Low_Effective=mean(Low<Placebo),High_Effective=mean(High<Placebo) )
}

ans=sapply(237:253,EMPA_REG)
ans
825: 05/04(日)19:45 ID:Ie2Wyhjx(1) AAS
CRANからパッケージBESTが消えていたのでplotPostと同等機能の関数を復刻(不適当データ入力などエラー回避処理は面倒なのでやってない)。

画像リンク


This function helps visualize posterior distribution samples from Bayesian inference and displays various informative elements. It can show the mean, mode, median, a credible interval (either HDI or quantiles), the Region of Practical Equivalence (ROPE), and a comparison value.

Arguments:

posterior_samples: A numeric vector of posterior distribution samples.
credMass: The width of the credible interval (a numeric value between 0 and 1; default is 0.95).
ROPE: A numeric vector specifying the ROPE range (e.g., c(lower_bound, upper_bound)).
compVal: A numeric value for comparison.
showMean: A logical value indicating whether to display the mean (TRUE/FALSE).
showMode: A logical value indicating whether to display the mode (TRUE/FALSE).
showMedian: A logical value indicating whether to display the median (TRUE/FALSE).
showCurve: A logical value indicating whether to display a density plot (TRUE/FALSE; if FALSE, a histogram is shown).
showQuantile: A logical value indicating whether to display the credible interval as quantiles instead of HDI (TRUE/FALSE).
xlab: The label for the x-axis.
main: The title of the plot.
hist_color: The color of the histogram.
textSize: The size of the text elements.
yaxt: The y-axis style (default is to show only numbers).
...: Additional arguments to be passed to the plotting function.
826: 05/05(月)19:07 ID:LDY1RQtT(1/4) AAS
# This R function, riskratio.boot, calculates the risk ratio and its Highest Density Interval (HDI)
# using a bootstrap method. It takes the number of events and the total number of observations
# for two groups as input.

riskratio.boot <- function(r1, r2, n1, n2, nboot = 5000, conf.level = 0.95, verbose = FALSE){
# Combine the number of events and total observations for both groups.
r <- c(r1, r2)
n <- c(n1, n2)
# Create a 2x2 matrix representing the contingency table (number of events and non-events).
m <- cbind(r, n - r) ; m
# Perform bootstrap resampling to estimate the risk ratio distribution.
rr <- replicate(nboot, {
# Simulate the number of events in the first group by sampling with replacement
# from a population with the observed event rate.
sample(c(rep(1, r1), rep(0, n1 - r1)), n1, replace = TRUE) |> sum() -> R1
# Simulate the number of events in the second group similarly.
sample(c(rep(1, r2), rep(0, n2 - r2)), n2, replace = TRUE) |> sum() -> R2
# Calculate the risk ratio from the bootstrapped event counts.
(R1 / n1) / (R2 / n2)
})
# If verbose is TRUE, plot the posterior distribution of the risk ratio.
if(verbose){
source('plotpost.R') # Assuming 'plotpost.R' is a script for plotting posterior distributions.
plotpost(rr, compVal = 1, showCurve = 1, lwd = 4) # Plot the distribution with a comparison value of 1.
}
# Calculate the mean of the bootstrapped risk ratios.
b_mean <- mean(rr)
# Calculate the Highest Density Interval (HDI) of the bootstrapped risk ratios.
b_ci <- HDInterval::hdi(rr, credMass = conf.level)
# Return a list containing the bootstrap mean and the HDI.
list(b_mean = b_mean, b_ci = b_ci)
}

# Example usage of the riskratio.boot function.
riskratio.boot(244, 282, 2345, 2333)
827: 05/05(月)19:08 ID:LDY1RQtT(2/4) AAS
Description:

The `riskratio.boot` function in R estimates the risk ratio between two groups and provides its Highest Density Interval (HDI) using a bootstrap resampling approach. It takes the counts of events and the total number of observations for each of the two groups as input.

Usage:

riskratio.boot(r1, r2, n1, n2, nboot = 5000, conf.level = 0.95, verbose = FALSE)

Arguments:

* `r1`: The number of events in the first group.
* `r2`: The number of events in the second group.
* `n1`: The total number of observations in the first group.
* `n2`: The total number of observations in the second group.
* `nboot`: The number of bootstrap replicates to perform (default is 5000). A larger number of replicates generally provides more stable estimates.
* `conf.level`: The credibility level for the Highest Density Interval (HDI) (default is 0.95, corresponding to a 95% HDI).
* `verbose`: A logical value indicating whether to display a plot of the bootstrap distribution of the risk ratio (default is `FALSE`). If `TRUE`, it assumes a script named `plotpost.R` is available in the working directory for plotting.
828: 05/05(月)19:09 ID:LDY1RQtT(3/4) AAS
Details:

The function works by simulating the event outcomes in each group through bootstrap resampling. For each group, it draws `n1` (or `n2`) samples with replacement from a hypothetical population that has the observed proportion of events (`r1/n1` or `r2/n2`). The number of events in each resampled set (`R1` and `R2`) is then used to calculate a bootstrapped risk ratio `(R1/n1) / (R2/n2)`. This process is repeated `nboot` times to generate a distribution of risk ratios. The function then calculates the mean of this distribution and its Highest Density Interval (HDI), which represents the most credible range for the true risk ratio given the data and the bootstrap procedure.

If `verbose` is set to `TRUE`, the function attempts to plot the distribution of the bootstrapped risk ratios using a script named `plotpost.R`. This requires that the `plotpost.R` script exists in the current working directory and is capable of handling the vector of bootstrapped risk ratios.

Value:

The function returns a list with the following components:

* `b_mean`: The mean of the bootstrapped risk ratios.
* `b_ci`: The Highest Density Interval (HDI) of the bootstrapped risk ratios, as a vector with the lower and upper bounds.

Note:

The `verbose = TRUE` option depends on an external script `plotpost.R`. If you intend to use this option, ensure that the script is available and correctly implemented for plotting posterior-like distributions. The HDI is calculated using the `hdi` function from the `HDInterval` package, so this package must be installed (`install.packages("HDInterval")`) and loaded (`library(HDInterval)`) if you intend to use the default behavior.
829: 05/05(月)19:23 ID:LDY1RQtT(4/4) AAS
> riskratio.boot(244,282,2345,2333,nboot=10000)
$b_mean
[1] 0.8641319

$b_ci
lower upper
0.7312212 1.0106121
attr(,"credMass")
[1] 0.95
830: 05/09(金)06:19 ID:vIVXuysf(1) AAS
SequentialPrimeDigits[n_Integer] :=
Module[{p = 10, result = {}},
While[Length[result] < n,
If[PrimeQ[p] && AllDifferencesAreOneQ[p],
AppendTo[result, p]
];
p++
];
result
]

AllDifferencesAreOneQ[num_Integer] :=
Differences[IntegerDigits[num]] === ConstantArray[1, Length[IntegerDigits[num]] - 1]

SequentialPrimeDigits[5]

{23, 67, 89, 4567, 23456789}

SequentialPrimeDigits[20]
831: 05/10(土)11:02 ID:ynDPH7B8(1/2) AAS
# ------------------------------------------------------------------------------
# ファイル名:logistic_regression_uraguchi_factors.R
# 目的:裏口入学の決定要因を評価するロジスティック回帰分析
# 考察対象の説明変数:学力、大学ランク (基準カテゴリ: A)、縁故、親の所得、寄付金
# ------------------------------------------------------------------------------

# データ生成 (大学ランクを因子型、基準レベル A)
set.seed(123)
n <- 1000
ranks_char <- sample(LETTERS[1:6], n, replace = TRUE)
ranks_factor <- factor(ranks_char, levels = LETTERS[1:6], ordered = TRUE) # 順序付きファクターとして生成

data <- data.frame(
裏口入学 = rbinom(n, 1, 0.2),
学力 = rnorm(n, mean = 50, sd = 10),
大学ランク = ranks_factor,
縁故 = rbinom(n, 1, 0.1),
親の所得 = rlnorm(n, meanlog = log(5000), sdlog = 0.3),
寄付金 = rlnorm(n, meanlog = log(100000), sdlog = 1.0)
)

# 支払額の生成
rank_numeric <- as.numeric(data$大学ランク) # A=1, B=2, ... 6
data$支払額 <- 10 * pmax(
300 + 100 * data$裏口入学 +
0.5 * (100 - data$学力) +
20 * rank_numeric +
50 * data$縁故 +
0.05 * data$親の所得 +
0.001 * data$寄付金 +
rnorm(n, mean = 0, sd = 50),
0
)

# ロジスティック回帰モデル (大学ランクが因子型として扱われ、基準カテゴリは A)
model_full <- glm(裏口入学 ~ 学力 + 大学ランク + 縁故 + 親の所得 + 寄付金, data = data, family = binomial)

# オッズ比と信頼区間の算出
confint_vals <- exp(confint(model_full))
odds_ratios_ci <- data.frame(
Variable = rownames(confint_vals)[-1],
CI_lower = confint_vals[-1, 1],
CI_upper = confint_vals[-1, 2]
)

# プロット用の変数ラベルを日本語化
label_map <- c(
"学力" = "学力",
"大学ランク.L" = "大学ランク B",
"大学ランク.Q" = "大学ランク C",
"大学ランク.C" = "大学ランク D",
"大学ランク^4" = "大学ランク E",
"大学ランク^5" = "大学ランク F",
"縁故" = "縁故",
"親の所得" = "親の所得",
"寄付金" = "寄付金"
)
odds_ratios_ci$日本語変数名 <- ifelse(odds_ratios_ci$Variable %in% names(label_map),
label_map[odds_ratios_ci$Variable],
odds_ratios_ci$Variable)
832: 05/10(土)11:02 ID:ynDPH7B8(2/2) AAS
# 現在の par() の設定を保存
current_par <- par(no.readonly = TRUE)

# 指定された mar と bty で描画
par(mar = c(5, 8, 5, 2), bty = 'l')

# plot 関数を使用したオッズ比の信頼区間プロット (1を基準)
n_vars <- nrow(odds_ratios_ci)
y_positions <- n_vars:1
xlim_odds <- range(odds_ratios_ci$CI_lower, odds_ratios_ci$CI_upper)

plot(NA, xlim = xlim_odds,
ylim = c(0.5, n_vars + 0.5),
xlab = "オッズ比 (log scale)",
ylab = "",
main = "ロジスティック回帰分析:オッズ比の95%信頼区間",
log = "x",
yaxt = "n")

segments(x0 = odds_ratios_ci$CI_lower,
x1 = odds_ratios_ci$CI_upper,
y0 = y_positions,
y1 = y_positions,
col = "skyblue",
lwd = 4)

abline(v = 1, lty = "dashed", col = "black")

# y軸のラベルを日本語で追加
axis(side = 2, at = y_positions, labels = odds_ratios_ci$日本語変数名[order(y_positions, decreasing = TRUE)], las = 1)

# 描画後に元の par() の設定に戻す
par(current_par)
833: 05/11(日)21:13 ID:2CgV4g4d(1) AAS
# データ設定
n_placebo <- 1000; eff_placebo <- 24
n_old <- 1000; eff_old <- 40
n_new <- 1000; eff_new <- 25

# 有効率
p_placebo <- eff_placebo / n_placebo
p_old <- eff_old / n_old
p_new <- eff_new / n_new

# 比較:旧薬 vs 偽薬(有意差)
m1 <- matrix(c(eff_old, n_old - eff_old, eff_placebo, n_placebo - eff_placebo), nrow = 2)
test1 <- prop.test(m1, correct = FALSE)

# 比較:新薬 vs 偽薬(有意差なし)
m2 <- matrix(c(eff_new, n_new - eff_new, eff_placebo, n_placebo - eff_placebo), nrow = 2)
test2 <- prop.test(m2, correct = FALSE)

# 比較:旧薬 vs 新薬(非劣性検定)
# 非劣性マージン
M <- -0.10
# 差(新薬 - 旧薬)
diff <- p_new - p_old
# 標準誤差(差の95%信頼区間に使用)
se <- sqrt(p_new*(1 - p_new)/n_new + p_old*(1 - p_old)/n_old)
z <- qnorm(0.025, lower.tail = FALSE)
lower_CI <- diff - z * se

# 非劣性判定
non_inferior <- lower_CI > M

# 結果表示
cat("=== 旧薬 vs 偽薬 ===\n")
print(test1)
cat("\n=== 新薬 vs 偽薬 ===\n")
print(test2)
cat("\n=== 非劣性検定(旧薬 vs 新薬) ===\n")
cat(sprintf("差(新薬 - 旧薬) = %.3f\n", diff))
cat(sprintf("95%% CI = [%.3f, %.3f]\n", diff - z*se, diff + z*se))
cat(sprintf("非劣性マージン = %.3f\n", M))
cat(sprintf("非劣性判定: %s\n", ifelse(non_inferior, "非劣性あり", "非劣性なし")))
834: 05/13(火)13:21 ID:L+Wotuil(1/2) AAS
ド底辺シリツ医大の三法則を与えたらAIが12法則まで拡張してくれました。

ド底辺医大の十二箇条 (The Twelve Laws of Do-Teihen Medical School)

第1法則
ド底辺シリツ医大が悪いのではない、本人の頭が悪いんだ。
It is not the bottom medical school but its enrollee that is despicable, which deserves to be called a bona fide moron beyond redemption.

第2法則
ド底辺シリツ医大卒は恥ずかしくて、学校名を皆さま言いません。
The graduates of Do-Teihen are so ashamed that none of them dare to mention their own alma mater they had gone through.

第3法則
ド底辺特殊シリツ医大卒は裏口入学の負い目から裏口馬鹿を暴く人間を偽医者扱いしたがる。
The Do-Teihen graduates are so ashamed of having bought their way into the exclusively bottom-leveled medical school that they tend to call a genuine doctor a charlatan who elucidates their imbecility.

第4法則
ド底辺医大卒は、偏差値や出身校を気にするなと言いながら、自分の子どもには絶対にそんな大学へは行かせたくないと思っている。
While claiming that academic ranking or alma mater does not matter, a Do-Teihen graduate would never let their own child attend such a university.

第5法則
ド底辺医大卒は、裏口入学を否定しない。否定できない。なぜなら、実際に自分がそうだからである。
A Do-Teihen graduate never denies the existence of backdoor admissions—because deep down, they know they were one of them.

第6法則
ド底辺医大は、「差別するな」と叫びながら、偏差値・財力・コネがない者を最もあからさまに差別する。
While crying out against discrimination, Do-Teihen medical schools are the very institutions that blatantly discriminate against those without test scores, wealth, or connections.
835: 05/13(火)13:21 ID:L+Wotuil(2/2) AAS
第7法則
ド底辺医大卒は「実力で入った」と言うが、その“実力”の定義を決して口にしない。
A Do-Teihen graduate may claim, “I got in on merit,” but they will never define what that 'merit' actually was.

第8法則
ド底辺医大卒の最大の敵は、同級生ではなく、偏差値という現実である。
The greatest enemy of a Do-Teihen graduate is not their classmates—but the cold, numerical reality of standardized test scores.

第9法則
ド底辺医大では、人格者は浮く。媚びる者とカネ持ちが残る。
In Do-Teihen med schools, the virtuous are outcasts; only flatterers and the wealthy thrive.

第10法則
ド底辺医大に入る者は、嘘をついて入学し、嘘をつき続けて卒業する。
Those who enter Do-Teihen medical schools do so with lies—and graduate by continuing to lie.

第11法則
ド底辺医大卒は、知性を持つ批判者を最も憎む。それは、自分が決してなれない姿だからだ。
Graduates of Do-Teihen reserve their deepest hatred for intelligent critics—because those critics reflect everything they can never become.

第12法則
ド底辺医大は、医者を育てる場ではない。医師免許を与える「通行証発行所」である。
Do-Teihen is not a school to train doctors. It is a toll booth that issues medical licenses for a price.
836: 05/15(木)15:07 ID:vFdoSXtm(1) AAS
rm(list=ls())

library(PropCIs)
noninferior.pitfall <- function(r0,n0, r1,n1, r2,n2, r3,n3, nim_coef, alpha=0.05, yates=FALSE) {
delta <- (r0/n0 - r1/n1) * nim_coef
if (min(r0, r1, r2, r3) < 5) {
p1 <- fisher.test(matrix(c(r1, n1-r1, r0, n0-r0), 2, 2))$p.value
p2 <- fisher.test(matrix(c(r2, n2-r2, r0, n0-r0), 2, 2))$p.value
ci_upper <- diffscoreci(r2, n2, r3, n3, conf.level=1-2*alpha)$conf.int[2]
} else {
p1 <- prop.test(c(r1, r0), c(n1, n0), correct=yates)$p.value
p2 <- prop.test(c(r2, r0), c(n1, n0), correct=yates)$p.value
ci_upper <- prop.test(c(r2, r1), c(n2, n1), conf.level=1-2*alpha, correct=yates)$conf.int[2]
}
all(
r1 < r0 && p1 < alpha,
p2 > alpha,
ci_upper < delta
)
}

noninferior.pitfall(16,201,6,202,7,203,6,204,0.684)
837
(1): 05/16(金)16:37 ID:s89ybxV8(1) AAS
イベント発生が人数比で
臨床試験1で 旧薬 vs プラセボで 5/201 vs 19/202
臨床試験2で 新薬 vs 旧薬 で  9/203 vs 5/204
であったとき
(1) 新薬がプラセボより劣る確率を計算せよ。
(2) 新薬はプラセボより有意差をもって有効といえるか?
計算に必要な条件は適宜設定してよい。
例:イベント発生は独立事象である

library(rjags)
library(coda)

worth_than_placebo <- function(r0, n0, r1, n1, r2, n2, r3, n3){
model_string <- '
model {
# 試験 (旧薬 vs 偽薬)
r1 ~ dbin(p1, n1)
p1 ~ dbeta(1, 1)
r0 ~ dbin(p0, n0)
p0 ~ dbeta(1, 1)

# 試験 (新薬 vs 旧薬)
r2 ~ dbin(p2, n2)
p2 ~ dbeta(1, 1)
r3 ~ dbin(p3, n3)
p3 ~ dbeta(1, 1)

# parameters
p2_est <- p2
p0_est <- p0
p2_worse_than_p0 <- step(p2_est - p0_est)
}
'
data <- list(r1=r1 , n1=n1 , r0=r0 ,n0=n0, r2=r2 , n2=n2 , r3=r3 , n3=n3)
jags_model <- jags.model(file=textConnection(model_string), data=data, n.chains=3,
n.adapt=3000, quiet = TRUE)
update(jags_model, n.iter=2000)
jags_samples <- coda.samples(jags_model, variable.names=c("p2_est", "p0_est", "p2_worse_than_p0"),
n.iter=10000, thin=1)
summary(jags_samples)
js <- as.data.frame(as.matrix(jags_samples))
names(js)

source("plotpost.R")
layout(matrix(c(1,2,3,3), 2, 2, byrow=TRUE))
plotpost(js$p2_est, col='lightcoral',xlab="新薬",cex.lab=1.5,main="")
plotpost(js$p0_est, col='lightgray', xlab="プラセボ",cex.lab=1.5,main="")
plotpost(js$p0_est - js$p2_est, compVal = 0, col=c('lightcoral', 'lightgray'),
xlab="プラセボ - 新薬", main="",cex.lab=1.5)
HDInterval::hdi(js$p0_est - js$p2_est) |> print()
mean(js$p2_worse_than_p0)
}

result <- worth_than_placebo(r0=19, n0=202, r1=5, n1=201, r2=9, n2=203, r3=5, n3=204)
print(paste("新薬がプラセボより劣る確率:", result))
838: 05/17(土)02:21 ID:zAzyVzie(1) AAS
>>837
# --- 必要パッケージ ---
library(rjags)
library(coda)
library(HDInterval)

# --- データ定義 ---
data_list <- list(
r0 = 19, n0 = 202, # プラセボ
r1 = 5, n1 = 201, # 旧薬(試験1)
r2 = 9, n2 = 203, # 新薬
r3 = 5, n3 = 204 # 旧薬(試験2)
)

# --- 階層モデル定義 ---
model_hier <- "
model {
r0 ~ dbin(p0, n0)
r1 ~ dbin(p1, n1)
r2 ~ dbin(p2, n2)
r3 ~ dbin(p3, n3)

p0 ~ dbeta(1, 1)
p2 ~ dbeta(1, 1)

mu_old ~ dbeta(1, 1)
tau ~ dgamma(0.001, 0.001) # 弱情報事前分布
p1 ~ dbeta(mu_old * tau, (1 - mu_old) * tau)
p3 ~ dbeta(mu_old * tau, (1 - mu_old) * tau)

p2_worse_than_p0 <- step(p2 - p0)

rd_p0_p1 <- p0 - p1
rd_p1_p2 <- p1 - p2
rd_p0_p3 <- p0 - p3

}
"

jags_model <- jags.model(textConnection(model_hier),
data = data_list, n.chains = 2, quiet=TRUE)
update(jags_model, 3000, progress.bar="none")
jags_samples <- coda.samples(jags_model,
c("p0","p1","p2","p3",
"p2_worse_than_p0", "rd_p0_p1","rd_p1_p2", "rd_p0_p3"),
n.iter=10000, progress.bar="none")
gelman.plot(jags_samples)
plot(jags_samples)

js <- as.data.frame(as.matrix(jags_samples))
mean(js$p2_worse_than_p0)
hdi(js$rd_p0_p1) # 旧薬(試験1) vs プラセボ
hdi(js$rd_p1_p2) # 旧薬(試験2) vs 新薬
hdi(js$rd_p0_p3) # 旧薬(試験2) vs プラセボ 仮想
hdi(js$p0-js$p2) # 新薬     vs プラセボ 仮想

source("plotpost.R")
layout(matrix(c(1,2,3,3), 2, 2, byrow=TRUE))
plotpost(js$p2, col='lightcoral',xlab="新薬",cex.lab=1.5,main="")
plotpost(js$p0, col='lightgreen', xlab="プラセボ",cex.lab=1.5,main="")
plotpost(js$p0 - js$p2, compVal = 0, col=c('lightcoral', 'lightgreen'),
xlab="プラセボ - 新薬", cex.main=2,main="二項分布階層モデル",cex.lab=1.5, breaks="scott")
839: 05/17(土)07:49 ID:Vpav5/5q(1) AAS
library(meta)
library(gemtc)

# データフレームの作成
data <- data.frame(
study = factor(c(1, 1, 2, 2)),
treatment = factor(c("Placebo", "Old", "Old", "New")),
events = c(19, 5, 5, 9),
total = c(202, 201, 204, 203)
)

# 治療効果の比較リスト
comparisons <- c("New - Placebo")

# ネットワークオブジェクトの作成
network <- mtc.network(data = data)

# ランダム効果モデルによるメタアナリシス
model <- mtc.model(network, type = "consistency", likelihood = "binom", link = "logit", linearModel = "random")

# モデルの実行
results <- mtc.run(model)

# 結果の概要
summary(results)

# 新薬 vs プラセボ の効果量(オッズ比)と95%信頼区間
relative.effect(results, "New", "Placebo")

# 新薬がプラセボより劣る確率(P(OR > 1))を推定
prob.superiority <- 1 - pnorm(0, mean = results$sol[grep("d.New", names(results$sol))], sd = results$se[grep("d.New", names(results$se))])
cat("新薬がプラセボより劣る確率 (間接推定):", prob.superiority, "\n")

# 新薬がプラセボに対して有意に有効かどうかの評価
# オッズ比の95%信頼区間に1が含まれるかどうかで判断
or.new.vs.placebo <- exp(results$sol[grep("d.New", names(results$sol))])
ci.lower <- exp(results$sol[grep("d.New", names(results$sol))] - 1.96 * results$se[grep("d.New", names(results$se))])
ci.upper <- exp(results$sol[grep("d.New", names(results$sol))] + 1.96 * results$se[grep("d.New", names(results$se))])

cat("新薬 vs プラセボ オッズ比 (間接推定):", or.new.vs.placebo, "\n")
cat("95%信頼区間:", ci.lower, "-", ci.upper, "\n")

if (ci.upper < 1) {
cat("新薬はプラセボに対して有意に有効である可能性が高いです。\n")
} else if (ci.lower > 1) {
cat("新薬はプラセボに対して有意に劣る可能性があります。\n")
} else {
cat("新薬とプラセボの間に有意な差は見られない可能性があります。\n")
}
840: 05/20(火)23:31 ID:gwaBTE4C(1) AAS
library(R2jags)

# データ
data <- list(
nA1 = 100, rA1 = 80, # Study1: 治療A
nB1 = 100, rB1 = 40, # Study1: 治療B
nA2 = 100, rA2 = 10, # Study2: 治療A
nC2 = 100, rC2 = 5 # Study2: 治療C
)

# JAGSモデル(textConnection使用)
model_code <- "
model {
# 尤度関数
rA1 ~ dbin(pA1, nA1)
rB1 ~ dbin(pB1, nB1)
rA2 ~ dbin(pA2, nA2)
rC2 ~ dbin(pC2, nC2)

# 治療Aの階層モデル
mu_A ~ dbeta(1, 1)
tau_A ~ dgamma(0.001, 0.001)
pA1 ~ dbeta(mu_A * tau_A, (1 - mu_A) * tau_A)
pA2 ~ dbeta(mu_A * tau_A, (1 - mu_A) * tau_A)
sigma_A <- 1 / sqrt(tau_A) # SDに変換

# 治療BとCも階層化(平均リスクを別々に推定)
mu_B ~ dbeta(1, 1)
mu_C ~ dbeta(1, 1)
pB1 ~ dbeta(mu_B * 100, (1 - mu_B) * 100) # 高い精度を仮定
pC2 ~ dbeta(mu_C * 100, (1 - mu_C) * 100)

# リスク差
RD_A1_B1 <- pA1 - pB1
RD_A2_C2 <- pA2 - pC2
RD_B1_C2 <- pB1 - pC2 # B vs Cの直接比較
}
"

# JAGS実行
jags_model <-
(textConnection(model_code),
data = data, n.chains = 3, quiet=TRUE)
update(jags_model, 3000) #, progress.bar="none")
jags_samples <- coda.samples(jags_model,
c("mu_A", "sigma_A", "RD_A1_B1", "RD_A2_C2", "RD_B1_C2", "pA1", "pA2", "pB1", "pC2"),
n.iter=10000) # , progress.bar="none")
gelman.plot(jags_samples)
plot(jags_samples)

summary(jags_samples)
jags_samples |> as.matrix() |> as.data.frame() -> js
names(js)
841: 05/23(金)10:58 ID:or+7Cxzr(1) AAS
#
"
Construct a Monte Carlo study that investigates how the probability of coverage depends on the sample size and true proportion value. In the study, let n be 10, 25, 50, and 100 and let p be .05, .25, and .50. Write an R function that has three inputs, n, p, and the number of Monte Carlo simulations m,and will output the estimate of the exact coverage probability.
Implement your function using each combination of n and p and m = 1000 simulations.
Describe how the actual probability of coverage of the traditional interval depends on the sample size and true proportion value.
"

f = \(n,p,m=1000){
y=rbinom(m,n,p)
phat=y/n
se=sqrt(phat*(1-phat)/n)
lo=phat - qnorm(0.975)*se
up=phat + qnorm(0.975)*se
mean(lo < p & p < up)
}
f=Vectorize(f)

n_values = c(10, 25, 50,100)
p_values = c(0.05, 0.25, 0.5)
set.seed(123)
outer(n_values,p_values,f)
842: 05/24(土)02:35 ID:VetM3rz7(1/5) AAS
LearnBayes::beta.selectをoptimを使って算出

beta.optim <- function(x1, p1, x2, p2, verbose = TRUE) {
# -------------------------
# モーメント近似による初期値推定
# -------------------------
mu0 <- (x1 + x2) / 2 # 仮の平均
sigma2 <- ((x2 - x1) / 4)^2 # 仮の分散(中間50%幅から)
v <- mu0 * (1 - mu0) / sigma2 - 1
a0 <- mu0 * v
b0 <- (1 - mu0) * v
start <- c(a0, b0)

# -------------------------
# 最適化対象の誤差関数定義
# -------------------------
objective <- function(params) {
a <- params[1]
b <- params[2]
# pbeta による累積確率との差を2乗誤差で評価
err1 <- pbeta(x1, a, b) - p1
err2 <- pbeta(x2, a, b) - p2
return(err1^2 + err2^2)
}

# -------------------------
# 最適化(境界付き)
# -------------------------
result <- optim(
par = start,
fn = objective,
method = "L-BFGS-B",
lower = c(1e-4, 1e-4) # ベータ分布は a, b > 0
)

# -------------------------
# 結果の取り出し
# -------------------------
a_hat <- result$par[1]
b_hat <- result$par[2]

if (verbose) {
cat("推定されたパラメータ: a =", round(a_hat, 4),
", b =", round(b_hat, 4), "\n")
cat("pbeta(x1) =", round(pbeta(x1, a_hat, b_hat), 4),
"(目標:", p1, ")\n")
cat("pbeta(x2) =", round(pbeta(x2, a_hat, b_hat), 4),
"(目標:", p2, ")\n")
}

# -------------------------
# 結果を返す
# -------------------------
return(list(a = a_hat, b = b_hat, ss_value = result$value))
}
843: 05/24(土)08:17 ID:VetM3rz7(2/5) AAS
library(rjags)

# Fit a Bayesian logistic regression model using JAGS and return predictions and posterior summaries
fit_bayesian_logistic_jags <- function(data, formula, newdata,
n.chains = 3, n.iter = 5000, n.burnin = 1000) {
# Extract response variable name from the formula
response_var <- all.vars(formula)[1]
y <- data[[response_var]]

# Convert factor response to binary numeric (0/1)
if (is.factor(y)) y <- as.numeric(y) - 1
y <- as.numeric(y)

# Construct design matrices for training and new data
X <- model.matrix(formula, data)
new_X <- model.matrix(delete.response(terms(formula)), newdata)

# Prepare data list for JAGS
jags_data <- list(
y = y,
X = X,
n = nrow(X),
p = ncol(X),
new_X = new_X,
scale_beta = rep(2.5, ncol(X)) # Prior scale for each coefficient
)

# Define the JAGS model
model_string <- "
model {
for (j in 1:p) {
beta[j] ~ dt(0, 1 / pow(scale_beta[j], 2), 1)
}

for (i in 1:n) {
logit_p[i] <- inprod(X[i,], beta[])
y[i] ~ dbern(1 / (1 + exp(-logit_p[i])))
}

new_logit <- inprod(new_X[1,], beta[])
new_p <- 1 / (1 + exp(-new_logit))
}
"

# Initialize and run the JAGS model
model <- jags.model(textConnection(model_string), data = jags_data,
n.chains = n.chains, quiet = TRUE)
update(model, n.burnin)

# Draw posterior samples
samples <- coda.samples(model, c("beta", "new_p"), n.iter - n.burnin)
mat <- as.matrix(samples)

# Return results
list(
model = samples,
predicted_prob = mean(mat[, "new_p"]),
summary = summary(samples)
)
}
844: 05/24(土)08:18 ID:VetM3rz7(3/5) AAS
# Example data
data <- data.frame(
donation = c(0, 1000, 2000, 0, 3000, 0, 4000, 0, 5000, 0),
score = c(90, 40, 35, 88, 30, 85, 25, 92, 20, 89),
parent = c(0, 1, 1, 0, 1, 0, 1, 0, 1, 0),
admission = as.factor(c(0, 1, 1, 0, 1, 0, 1, 0, 1, 0))
)

# New observation to predict
newdata <- data.frame(
donation = 2500,
score = 40,
parent = 1
)

# Fit model and obtain results
set.seed(123)
result <- fit_bayesian_logistic_jags(
data = data,
formula = admission ~ donation + score + parent,
newdata = newdata
)

# Extract variable names including intercept
var_names <- colnames(model.matrix(admission ~ donation + score + parent, data))

# Extract beta coefficient summaries
beta_stats <- result$summary$statistics[grep("^beta\\[", rownames(result$summary$statistics)), c("Mean", "SD")]
beta_quants <- result$summary$quantiles[grep("^beta\\[", rownames(result$summary$quantiles)), c("2.5%", "97.5%")]

# Rename row names using variable names
rownames(beta_stats) <- var_names
rownames(beta_quants) <- var_names

# Display results
print(beta_stats)
print(beta_quants)
cat("Predicted probability:", round(result$predicted_prob, 3), "\n")
1-
あと 147 レスあります
スレ情報 赤レス抽出 画像レス抽出 歴の未読スレ

ぬこの手 ぬこTOP 0.022s