# deviance explained: 1 - [Residual Deviance] / [Null Deviance]
dev.exp <- function(x){ # xはglmの結果
list("Deviance explained" = 1 - x$deviance / x$null.deviance,
"Null Deviance" = x$null.deviance,
"Residual Deviance" = x$deviance)
}
# # 準備(rmutilとgnlmのインストール)
# http://popgen.unimaas.nl/~jlindsey/rcode.htmlから以下のファイルを入手して,インストールする
# http://popgen.unimaas.nl/~jlindsey/rcode/rmutil.zip
# http://popgen.unimaas.nl/~jlindsey/rcode/gnlm.zip
dist <-rnorm(1000)
poi <-rpois(1000, exp(1.5 +0.8 * dist))
table(poi) # データの確認(結果は省略)
mean(poi) # 平均値
# [1] 6.369
var(poi) # 分散
# [1] 52.48132
# 0過剰(zero-inflated)にする
inf.poi <- poi # 基本はポワソン分布
inf <- rbinom(1000, 1, 0.7) # 7:3の2項分布を発生
table(inf) # データを確認(結果は省略)
# inf
# 0 1
# 286 714
inf.poi[inf==0] <- 0 # infが0のところはポワソン分布のデータを0にして0を過剰にする
table(inf.poi) # データの分布を確認
mean(inf.poi) # 平均値が変化している
# [1] 4.322
var(inf.poi) # 分散が変化している
# [1] 35.54386
library(rmutil)
library(gnlm)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
gnlr(inf.poi, distribution="Poisson", mu=~exp(b0+b1*dist), pmu=c(b0=1,b1=0))
# Call:
# gnlr(inf.poi, distribution = "Poisson", mu = ~exp(b0 + b1 * dist),
# pmu = c(b0 = 1, b1 = 0))
#
# Poisson distribution
#
# Response: inf.poi
#
# Log likelihood function:
# {
# m <- mu1(p)
# -sum(wt * (-m + y * log(m)))
# }
#
# Location function:
# ~exp(b0 + b1 * dist)
#
# -Log likelihood 3127.206
# Degrees of freedom 998
# AIC 3129.206
# Iterations 10
#
# Location parameters:
# estimate se
# b0 1.2021 0.01851
# b1 0.6916 0.01402
#
# Correlations:
# 1 2
# 1 1.00 -0.57
# 2 -0.57 1.00
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
fmr(inf.poi, distribution="Poisson", mu=~exp(b0+b1*dist), pmu=c(b0=1,b1=0), pmix=0)
#
# Call:
# fmr(inf.poi, distribution = "Poisson", mu = ~exp(b0 + b1 * dist),
# pmu = c(b0 = 1, b1 = 0), pmix = 0)
#
# Poisson distribution
#
# Response: inf.poi
#
# Log likelihood function:
# {
# m <- mu1(p)
# s <- mixt(p)
# -sum(wt * log((1 - s) * cens + s * dpois(y, m)))
# }
#
# Location function:
# ~exp(b0 + b1 * dist)
#
# Mixture function:
# exp(p[1])/(1 + exp(p[1])) * rep(1, n)
#
# -Log likelihood 2000.778
# Degrees of freedom 997
# AIC 2003.778
# Iterations 13
#
# Location parameters:
# estimate se
# b0 1.498 0.01993
# b1 0.801 0.01564
#
# Mixture parameters:
# estimate se
# p[1] 0.9546 0.07613
#
# Correlations:
# 1 2 3
# 1 1.0000 -0.6295 -0.1118
# 2 -0.6295 1.0000 0.1010
# 3 -0.1118 0.1010 1.0000
# Warning message:
# NA/Inf は正の最大値で置き換えられました
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# pに影響を及ぼす変数を組みこむ場合
# fmr(inf.poi, distribution="Poisson", mu=~exp(b0+b1*dist), pmu=c(b0=1,b1=0), mix=~b2+b3*dist, pmix=c(b2=0,b3=1))
library(R2WinBUGS) # R2WinBUGS のよみこみ
example(bugs) # モデルファイルやパラメーター・データが準備される
schools.sim <- bugs(
data, inits, parameters, model.file,
n.chains = 3, n.iter = 5000,
bugs.directory = "d:/pf/WinBUGS14/",
working.directory = NULL,
clearWD = TRUE,
debug = TRUE # これは FALSE でも動作する
)
print(schools.sim) # bugs オブジェクトのまとめ
plot(schools.sim) # bugs オブジェクトの作図
oneway.test(extra ~ group, data = sleep) # 等分散を仮定しない場合(デフォルト)
oneway.test(extra ~ group, data = sleep, var.equal = TRUE) # 等分散を仮定する場合
参考:一元配置分散分析
# 書式
# t.test(group1, group2, var.equal=F)
# 等分散を仮定しない
t.test(1:10, 7:20, var.equal=F)
t.test(1:10, c(7:20, 200), var.equal=F)
# 等分散を仮定する
t.test(1:10, 7:20, var.equal=T)
t.test(1:10, c(7:20, 200), var.equal=T)
library(cluster) # ライブラリの呼び出し
mat <- t(matrix(c(29,12,2, 9,26,5, 12,21,1, 15,15,10, 3,16,34, 9,4,18), ncol=6)) # 調査資料
cls <- agnes(mat) # 非加重平均法(UPGMA)
plot(cls) # 結果の図示
oneway.test(data, group) # http://aoki2.si.gunma-u.ac.jp/lecture/Average/oneway-ANOVA-r.html
kruskal.test(data, group) # http://aoki2.si.gunma-u.ac.jp/lecture/Average/kwtest-r.html
kruskal.wallis(data, group) # http://aoki2.si.gunma-u.ac.jp/R/kruskal-wallis.html
abs.lm <- function(x){
if(!class(x)=="lm" & !class(x)=="summary.lm") { # lmかsummary.lmかの確認
paste(x, "はlmでもsummary.lmでもありません", sep="")
} else {
if(class(x)=="lm") x <- summary(x) # lmをsummary.lmに変換
coef <- x$coefficients[,c(1,4)] # 推定値と有意水準
coef[,2] <- as.character(cut(coef[,2], breaks=c(0,0.001,0.01,0.05,1), # 有意水準を記号に変換
labels=c("***","**","*","n.s."),right=F))
coefficients <- data.frame(0) # 結果の入れ物を用意
for(i in 1:nrow(coef)){ # 行ごとに
coefficients <- cbind(coefficients, # 推定値と有意水準を結合
as.data.frame(paste(coef[i,1], coef[i,2], sep=" ")))
}
coefficients <- coefficients[-1] # 始めのデータを削除
colnames(coefficients) <- rownames(coef) # 列名を設定
coefficients <- cbind(coefficients, # 決定係数・データ数を追加
data.frame(r.squared=x$r.squared, adj.r.squared=x$adj.r.squared, n=length(x$residuals)))
coefficients
}
}
# 使用例
data(cars)
lm(cars$dist ~ cars$speed)
summary(lm(cars$dist ~ cars$speed))
abs.lm(lm(cars$dist ~ cars$speed))
> ## 行列の資料を散布図にする
mat.plot <- function(mat, trans=FALSE, horiz=FALSE, type="b", ...){ # 行列
if(trans==TRUE) mat <- t(mat) # 行列を入れ替える
lim <- range(mat)
m <- ncol(mat) # 列数
n <- nrow(mat) # 行数
plot(1, type="n", axes=F, ann=F) # 何も描かない
j <- round(n*3); k <- round((j-n)/2) # 色の設定
col <- grey((j:0/j)[k:(k+n)]) # 色の設定
for(i in 1:n){ # 各行で
par(new=T)
if(horiz==TRUE){
plot(x=1:m, y=mat[i,], xlim=c(1,m), ylim=lim, col=col[i], type=type, ...) # 散布図
} else {
plot(y=1:m, x=mat[i,], ylim=c(1,m), xlim=lim, col=col[i], type=type, ...) # 散布図
}
}
}
## 使用方法
matplot(matrix(1:20, nrow=4))
mat.plot(matrix(1:20, nrow=4), trans=F, horiz=F)
mat.plot(matrix(1:20, nrow=4), trans=F, horiz=T)
# 関数の定義
shift.plot <- function(df, cl=50, xmax=100,...){ # data.frame y軸の階級 x軸の幅
# 階級の区分
mn <- min(df[,1])
mx <- max(df[,1])
by=(mx-mn)/(cl-1) # 範囲/階級数
df <- cbind(df, cl=cut(df$n, seq(from=mn, to=mx+by, by=by), right=F))
df <- df[order(df[,2], df[,1]),]
# 近接した場合の移動量
freq <- na.omit(as.data.frame.table(tapply(df[,1], list(df[,3], df[,2]), length))) # 頻度
freq <- freq[order(freq[,2], freq[,1]),]
shift1 <- unlist(mapply(":", 1, freq[,3]))
df <- cbind(df, shift=shift1)
# 凡例別の移動量
shift2 <- xmax / (length(unique(freq[,2]))*2)
shift2 <- shift2 * seq(from=1, to=length(unique(freq[,2]))*2, by=2)
shift2 <- mapply(rep, shift2, tapply(df[,1], df[,2], length))
shift2 <- unlist(shift2[1:length(shift2)])
shift3 <- shift2 + xmax*0.01 # x軸の凡例の移動量 0.01を変更してズレを調整
# 移動量の合計
df$shift <- df$shift + shift2
plot(df$shift, df$n, xlim=c(0,xmax), xaxt="n", ...)
axis(side=1, at=unique(shift3), labels=as.character(unique(df[,2]))) # x軸を表示
}
# 使用方法
r <- 60
df <- data.frame(n=round(rnorm(r)*10,0), com=c(rep("a",r/2), rep("b",r/4), rep("c",r/4)))
shift.plot(df, cl=100, xmax=100)
library(spatstat) # ライブラリの呼び出し
data(cells) # データの呼び出し
# 密度分布図
par(mfrow=c(2,2)) # 2*2に分割
for(i in seq(from=0.07, to=0.08, by=0.01)){
Z <- density.ppp(cells, i) # 密度の推定
plot(Z, main = "Kernel smoothed intensity") # 密度分布
plot(cells, add = TRUE) # 散布図を追加
}
# 距離分布
Z <- distmap(cells, dimyx = 512)
plot(cells$window, main = "Distance map")
plot(Z, add = TRUE)
points(cells)
# 最も近い点を探す
plot(cells) # 散布図
m <- nnwhich(cells) # 最も近い点を探す
b <- cells[m] # 最も近い点との対応を作る
arrows(cells$x, cells$y, b$x, b$y, angle = 12, length = 0.1, col = "red") # 矢印で表示
# 透視図
persp(Z, colmap=terrain.colors(128), shade=0.3, phi=45, theta=30, main="perspective plot")
# 各種解析の要約表示
plot(allstats(cells)) # for unmarked point pattern
# その他使えそうな関数の一覧
library(spatstat) # ライブラリの呼び出し
unmark # 指標を取り除く
setmarks # 指標を付ける
%mark% # 指標を付ける
cut # 指標の操作
split # 指標の操作
cut.ppp # 数値の指標を因子(factor)の指標に変換
split.ppp # 指標の因子ごとに分割
superimpose # 点過程を統合
nndist # nearest neighbour distance
pairdist # distance between each pair of points
Gcross # Multitype Nearest Neighbour Distance Function (i-to-j)
Gdot # Multitype Nearest Neighbour Distance Function (i-to-any)
Gest # Nearest Neighbour Distance Function G
Gmulti # Marked Nearest Neighbour Distance Function
Jcross # Multitype J Function(i-to-j)
Jdot # Multitype J Function(i-to-any)
Jest # Estimatethe J-function
Jmulti # Marked J Function
Kcross # Multitype K Function (Cross-type)
Kdot # Multitype K Function (i-to-any)
kest # K-function
Kmulti # Marked K-Function
## 行列資料で行ごとの数値をヒストグラム(もどき)で表示する
mat.hist <- function(mat, omi=rep(0.5, 4), mai=rep(0, 4), ratio=NA, ...){ # 行列と余白の設定
if(is.na(ratio)) ratio <- sapply(as.data.frame(t(mat)), max) # 各行の最大値(グラフの割合)
n <- nrow(mat) # 列数
layout(matrix(1:n, nrow=n), heights=ratio, TRUE) # 作図画面を分割
par(omi=omi) # 全体の余白
par(mai=mai) # 個々の余白
for(i in 1:n){ #
barplot(mat[i,], axes=FALSE, space=0, ...) # ヒストグラム(みたいなもの)
axis(side=2, ...) # 個々のグラフのy軸
}
axis(side=1) # 全体のx軸
}
# 使用例
m <- matrix(abs(rnorm(100)), ncol=20) # 乱数を発生
mat.hist(m) # 図示
## レズリー行列を作る関数
make.reslie <- function(recruit, survive){ # (recruit:齢別出生数 survive:齢別期間生存率)
i <- length(recruit)
reslie <- matrix(0, nrow=i, ncol=i) # 0行列
reslie[1,] <- recruit # 齢別出生数
for(j in 1:(i-1)){ # 齢別期間生存率
reslie[j+1, j] <- survive[j]
}
reslie
}
## レズリー行列と初期値から個体群の動態を計算する
pop.dynamic <- function(reslie, initial, n=20){ # reslie:レズリー行列 initial:初期値 n:世代数
i <- ncol(reslie)
pop.dyn <- initial # 1世代目
pop <- reslie %*% initial # 2世代目
pop.dyn <- cbind(pop.dyn, pop)
for(j in 3:n){
pop <- reslie %*% pop # 3世代目以降
pop.dyn <- cbind(pop.dyn, pop)
}
pop.dyn
}
## 個体群の動態を散布図にする
plot.dynamic <- function(dy){
n <- ncol(dy) # 世代数
m <- nrow(dy) # 齢数
plot(dy[1,], type="b", log="y", ylim=c(min(dy),max(dy[1,]))) # 最小齢の動態の散布図
for(i in 2:m){ # 各齢の動態の散布図
par(new=T)
plot(dy[i,], type="b", log="y", ylim=c(min(dy),max(dy[1,])))
}
}
## レズリー行列と初期値から平衡に達するまでの動態を計算する
pop.equil <- function(reslie, initial, n=5){ # reslie:レズリー行列 initial:初期値 n:平衡後の世代数
i <- ncol(reslie)
pop.dyn <- initial # 1世代目
pop <- reslie %*% initial # 2世代目
pop.dyn <- cbind(pop.dyn, pop)
j <- 2 # 第2世代から開始
ratio.befor <- round(pop.dyn[,j-1] / sum(pop.dyn[,j-1]), 5) # 第1世代の頻度分布
ratio.after <- round(pop.dyn[,j] / sum(pop.dyn[,j]), 5) # 第2に世代の頻度分布
while(sum(ratio.befor!=ratio.after)>0){
pop <- reslie %*% pop # 3世代目以降
pop.dyn <- cbind(pop.dyn, pop)
ratio.befor <- round(pop.dyn[,j] / sum(pop.dyn[,j]), 5)
ratio.after <- round(pop.dyn[,j+1] / sum(pop.dyn[,j+1]), 5)
j <- j + 1 # 次の世代へ
}
for(k in 1:n){ # 平衡後n世代を計算
pop <- reslie %*% pop # 3世代目以降
pop.dyn <- cbind(pop.dyn, pop)
}
list(dynamics=pop.dyn, ramda = sum(pop.dyn[,j+n])/sum(pop.dyn[,j+n-1]))
}
## 基礎情報の設定
recruit <- c(0, 2, 3, 4, 1) # 齢別出生数
survive <- c(0.4, 0.7, 0.7, 0.7, 0) # 齢別期間生存率
initial <- c(10, 2, 2, 2, 2) # 初期値
initial2 <- c(1, 5, 1, 1, 1) # 初期値
## 計算・作図
reslie <- make.reslie(recruit, survive) # レズリー行列
dy <- pop.dynamic(reslie, initial, 15) # 個体群動態を計算
par(mfrow=c(1,3))
plot.dynamic(dy) # 個体群の動態から散布図を作図
dy2 <- pop.dynamic(reslie, initial2, 15)
plot.dynamic(dy2)
dy3 <- pop.equil(reslie, initial, n=10) # 平衡に達するまでを計算
plot.dynamic(dy3$dyn)
dy3 # 平衡に達するまでの動態と固有値(λ)
layout.plot.hist <- function(x,y, ratio1=c(3,1), ratio2=c(1,3)){
# (左下,左上,右下,右上)の順に(1,2,3,0) 0は描画しない 分割を縦横それぞれ設定
layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), ratio1, ratio2, TRUE)
# ヒストグラム情報を記録
x.counts <- hist(x, right=FALSE, plot=FALSE)$counts
y.counts <- hist(y, right=FALSE, plot=FALSE)$counts
# 左下画面
par(mar=c(3,3,1,1)) # 余白指定
plot(x, y, xlim=range(x), ylim=range(y)) # 散布図作成
# 左上画面
par(mar=c(0,3,1,1)) # 余白指定
barplot(x.counts, ylim=c(0,max(x.counts)), space=0, col=0) # 上ヒストグラム
# 右下画面
par(mar=c(3,0,1,1)) # 余白指定
barplot(y.counts, xlim=c(0,max(y.counts)), space=0, horiz=TRUE, col=0) # 右ヒストグラム
}
x <- runif(100) # 一様分布の乱数
y <- rnorm(100) # 正規分布の乱数
layout.plot.hist(x,y) # 作図
layout.plot.hist(x,y,c(1,1),c(1,1)) # 作図
layout.plot.hist2 <- function(x,y, x2,y2, ratio1=c(3,1), ratio2=c(1,3)){
# (左下,左上,右下,右上)の順に(1,2,3,0) 0は描画しない 分割を縦横それぞれ設定
layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), ratio1, ratio2, TRUE)
# ヒストグラム情報を記録
x.counts <- hist(x, right=FALSE, plot=FALSE)$counts
y.counts <- hist(y, right=FALSE, plot=FALSE)$counts
x.breaks <- hist(x, right=FALSE, plot=FALSE)$breaks
y.breaks <- hist(y, right=FALSE, plot=FALSE)$breaks
x2.counts <- hist(x2, right=FALSE, breaks=x.breaks, plot=FALSE)$counts
y2.counts <- hist(y2, right=FALSE, breaks=y.breaks, plot=FALSE)$counts
# 左下画面
par(mar=c(3,3,1,1)) # 余白指定
plot(x, y, xlim=range(x), ylim=range(y)) # 散布図作成
points(x2, y2, pch=16) # 塗りつぶし
# 左上画面
par(mar=c(0,3,1,1)) # 余白指定
barplot(x.counts, ylim=c(0,max(x.counts)), space=0, col=0) # 上ヒストグラム
barplot(x2.counts, ylim=c(0,max(x.counts)), space=0, col=1, add=T)
# 右下画面
par(mar=c(3,0,1,1)) # 余白指定
barplot(y.counts, xlim=c(0,max(y.counts)), space=0, horiz=TRUE, col=0) # 右ヒストグラム
barplot(y2.counts, xlim=c(0,max(y.counts)), space=0, horiz=TRUE, col=1, add=T)
}
x <- runif(100) # 一様分布の乱数
y <- rnorm(100) # 正規分布の乱数
x2 <- x[1:30] # 一様分布の乱数
y2 <- y[1:30] # 正規分布の乱数
layout.plot.hist2(x,y,x2,y2) # 作図
layout.plot.hist2(x,y,x2,y2,c(1,1),c(1,1)) # 作図
身長 <- c(147,162,170,155,168,164,172,171,151,157,174,172,163,189,185,189,181,171,183,178)
体重 <- c(57.5,58.9,72.1,49.7,68.8,52.7,74.1,60.5,52.6,48.5,74.0,72.4,60.4,79.8,76.2,75.1,72.7,73.4,78.2,67.5)
plot(体重~身長) # 本来の散布図
summary(lm(体重~身長)) # 本来の回帰分析
階級 <- cut(身長, breaks=seq(140,190,10), right=F, labels=c("145", "155", "165", "175", "185"))
階級値 <- tapply(体重, 階級, mean) # 階級ごとに平均値を算出
plot(階級値~as.numeric(names(階級値))) # 階級区分後の散布図
summary(lm(階級値~as.numeric(names(階級値)))) # 階級区分後の回帰分析
- 声に出して照合する(調査時の筆記では、必ず「復唱」をする)
データ確認用のプログラムを実行する
散布図やヒストグラムなどの図を作成する
2回データを入力する(2回の入力が異なるところは確認をする)
印刷をして確認する(確認したところは鉛筆で「はねる」)
割振った番号との照合などの場合は、チェックデジット(検査番号)を使用する
A⊃B:AはBを含有する。
A∪B:和集合。AかBかどちらかにあるもの(両方にあるものも含む)。
A∩B:積集合。AとBの共通するもの。
A−B:差集合。Aにあって、Bにないもの。
layer <- factor(c("k2","k1","b2","b1","k1","s2","k1","b1","s1","k1","s2","s1","b2","b1","k1","s2")) # 順位なし
layer # 順序がばらばら
table(layer) # 集計してもばらばら
layer <- ordered(layer, levels=c("k2","k1","s2","s1","b2","b1")) # 階層に順位を与える
layer # 順位がついている
table(layer) # 集計が順位どおりにならぶ
"collector": adds sites in the order they happen to be in the data (調査順に調査区を追加)
"random": adds sites in random order (無作為に調査区を追加)
"exact": finds the expected (mean) species richness (平均種数の期待値)
"coleman": finds the expected richness following Coleman et al. 1982 (Coleman(1982)による種数の期待値)
"rarefaction": finds the mean when accumulating individuals instead of sites (調査区でなく個体を追加)
abuocc # 種順位曲線 Abundance/Occurrence Graphical Analysis
brycesite # Bryce渓谷国立公園の地点データ Site Data for Bryce Canyon National Park
bryceveg # Bryce渓谷国立公園の植生データ Bryce Canyon Vegetation Data
const # Constancy Table
dga # 直接傾度分析 Direct Gradient Analysis
disana # 非類似度分析 Dissimilarity Analysis
dsvdis # 非類似度と距離 Dissimilarity Indices and Distance Measures
duarm # Indicator Species Analysis Minimizing Partial Occurrences
duleg # Dufrene-Legendreの指標種分析 Dufrene-Legendre Indicator Species Analysis
envrtest # Environmental Distribution Test
euclidify # Nearest Euclidean Spac eRepresentation of a Dissimilarity Object
importance # Importance Table
indspc # Compositional Indicator Species Analysis
metrify # Nearest Metric Space Representation of a Dissimilarity Object
nmds # Nonmetric Multidimensional Scaling
ordcomp # Ordination to Dissimilarity Comparison
ordpart # Ordination Partitioning
ordtest # Ordination Distribution Test
pca # 主成分分析 PrincipalComponentsAnalysis
pco # PrincipalCoordinatesAnalysis
plot.nmds # Plotting Routines For Nonmetric Multi-dimensional Scaling Ordinations
plot.pca # Plotting Routines For Principal Components Ordinations
plot.pco # Plotting Routines For Principal Coordinates Ordinations
rnddist # Random Distance
rndtaxa # Randomize a Taxa Data Frame
spcdisc # Species Discrimination Analysis
vardist # Variable Pairwise Difference
vegtab # Vegetation Table
vegtrans # Vegetation Data Transformation
cut.cluster <- function(agnes, div=2, c.name=paste("cluster",as.character(1:div),sep="")){
# 入力データ
# agnes:library(cluster) の関数 agness() で解析した結果
# div:分割数
# c.name:クラスターの名称
if(div!=length(c.name)) return("分割数とクラスターの名称数が異なります") # エラーチェック
c.point <- agnes$height # 結合点
stand <- agnes$order # 地点名
# 1つに分割の場合:全部同ラスター
if(div==1) return(data.frame(stand=stand, cluster=rep(c.name[1], length(c.point)+1)))
# 要素数以上に分割:全部違うクラスター
if(div>=length(c.point)) return(data.frame(stand=stand, cluster=paste("cluster",as.character(1:(length(c.point)+1)),sep="")))
thres <- sort(c.point, decreasing=T)[div] # 閾値を設定
j <- 1
cluster <- c.name[j]
for(i in 1:length(c.point)){
if(c.point[i]>thres) j <- j+1 # 次のクラスター
cluster <- c(cluster, c.name[j])
}
data.frame(stand=stand, cluster=cluster)
}
使用例
install.packages(c("cluster", "vegan")) # パッケージのインストール
library(vegan)
library(cluster)
data(dune)
cluster <- agnes(dune)
div.cluster(cluster)
source("d:/fv.r") # 関数の読込:関数を保存した場所を指定する
df <- std2df("D:/VegSample.txt") # 標準互換テキストを読み込んで表計算形式に変換
write.table(df$st, file="D:/st.txt", quote=F, sep="\t", row.names=F) # 地点関連データの出力
write.table(df$comp, file="D:/comp.txt", quote=F, sep="\t", row.names=F) # 組成関連データの出力
std <- df2std("D:/") # 表計算形式のデータを読み込んで標準互換テキストに変換
write.table(std, file="D:/std.txt", quote=F, row.names=F, col.names=F) # 標準互換テキストで出力
ピアソンの積率相関係数の表2
相関係数の解釈
相関係数の絶対値 解釈 解釈 0.0〜0.2 ほとんど相関関係がない ほとんど相関なし 0.2〜0.4 やや相関関係がある 弱い相関あり 0.4〜0.7 かなり相関関係がある やや相関あり 0.7〜1.0 強い相関関係がある かなり強い相関がある
matplot4 <- function(df, pch=NULL, ...){ # df:data1,data2,label
plot(df[[1]], df[[2]], type="n", ...) # 空のグラフ
label <- unique(df[[3]]) # ラベルの数
if(is.null(pch)) pch <- 1:length(label) # pchの指定無:通常の順番
for(i in 1:length(label)){ # ラベルごとに散布図を描画
sub.df <- subset(df, df[[3]]==label[i])
points(sub.df[[1]], sub.df[[2]], pch=pch[i], ...)
}
}
使用例
df <- list(x=rnorm(50), y=rnorm(50), z=sample(c("a","b","c","d","e","f"),10,replace=T))
df <- as.data.frame(df)
matplot4(df, pch=c(1,2,0,16,17,15))
plot(rep(1,6), pch=c(1, 2, 0, 16, 17, 15), cex=5) # cex でシンボルの大きさを5倍に変更
参考文献:トップジャーナルにアクセプトされる医学論文―執筆と投稿のキーポイント
pois.plot <- function(x, y=NULL, ...){ # x(種数など), y(環境傾度など) データフレームとして与えてもOK
if (is.null(y)){ y <- x[[2]]; x <- x[[1]] } # 引数が1つのデータフレームの場合はxとyに分割
pois <- glm(y ~ 1 + x, family = poisson(link = "log")) # ポワソン分布モデル
curve( exp(pois[[1]][1] + pois[[1]][2] * x), xlim=range(x), ...) # 推定した曲線を描画
points(x,y) # 散布図をプロット
summary(pois)
}
サンプルデータ
beta0 <- 4
beta1 <- -0.01
x <- seq(from = 0, to = 200, by = 2)
y <- exp(beta0 + beta1 * x)
sample <- rpois(length(y), lambda = y)
pois.plot(x,sample)
参考
http://aoki2.si.gunma-u.ac.jp/lecture/mb-arc/arc026/01281.html
http://cse.naro.affrc.go.jp/takezawa/r-tips/r/72.html
http://www1.doshisha.ac.jp/~mjin/R/15.pdf
1-2-2 p値の示し方(Exact p-value)
統計学的に有意でなかった検定の結果を、一律に“N.S.”や“not significant(有意差なし)”と示すよりも、例えばP=0.23のような実際のp値(Exact p-value)として示す方が望ましい。
表や図の中で示されるp値は本文の中で繰り返される必要はない。通常、p値は小数点以下3ケタ(P=0.025、P=0.003)まで示されるが、p値が0.1より大きい場合には、P=0.25のように小数点以下2ケタで充分である。非常に小さいp値の時はP < 0.001やP < 0.0001のように示して構わない。“p”でも“P”でもどちらでもよいがP(大文字イタリック)が国際標準である。
1-2-3 点推定値と信頼区間
2) 平均値は通常、元のデータを越える有効ケタ数を示す必要はないが、標準偏差や標準誤差は元のデータより1ケタ多く示す。割合をパーセントで示す場合、 56.47%というように小数点以下2ケタまで示す必要があることは稀であり、特に例数が少ない時には38.6%のように小数点1ケタを示すことも必要でない場合も多い。極めて少ない例数における割合の表示でパーセントを用いることは避けるべきである(例:1/1=100%、2/2=100%)。tや χ2、rのような検定統計量は小数点以下2ケタで充分である。ただし、これらの注意点は結果の表示の際の話であって、解析の途中では(切り上げ、切り捨て、四捨五入のような)まるめは行うべきではない。
2-1-3 統計学的有意性と臨床的意義
例数が充分に多い(sample sizeが大きい)場合は、小さい差であっても“統計学的有意”となりうる。仮想的には1500例以上を登録する無作為化比較試験では5年生存率で5%以下に相当する小さな(生存時間分布の)差を検出できることになる。こうした小さな差が仮に“統計学的に有意”であったとしても、個々の患者の治療においては臨床的に必ずしも重要であると言えない場合があるだろう。一方、例数が少なくて、非常に大きな差であっても“統計学的有意差”が得られない場合があるが、それが臨床的に重要な差であるとみなせるならば単に“有意差がない”として無視されるべきではなく、さらなる検討の対象とされる(新たな臨床研究を行う)べきであろう。研究者は「統計学的有意差」と「臨床的な重要性」を明確に区別する必要があり、“臨床的に意味のある差”を検出し得るような研究デザインを組むべきである。
2-1-5 確定的か探索的か?
確定的なデータ解析か、探索的なデータ解析かは常に区別されなければならない。
探索的データ解析の弱点は先述した多重性である。すべての探索的データ解析の結論は「さらなる検討を行う必要があり、かつその価値がある」か、「これ以上検討の価値がない」かのどちらかである。いかに“高度に有意な”結果が得られようとも基本的には同じである。なぜなら、予め計画された以外の探索的な解析では、自由に何通り(何十通り、何百通り)もの計算が可能であるため、意図したかそうでないかに関わらず“差のありそうな”比較に注目して進められた(“fishing”と呼ばれる)可能性が常にあり、“たまたまその時だけ偶然に出た(有意)差”を拾っているに過ぎないことを否定できないからである。