Rで単回帰
被験者×条件の数の単回帰を一気に行いたいという要望があったので,関数を作成。
関数
#被験者×条件数だけ単回帰を繰り返す #使い方 # 下の形のデータフレームを作ります。 # 1列目 = 被験者(文字でも数字でも可) # 2列目 = 条件(文字でも数字でも可) # 3列目 = x # 4列目 = y # rep_regression(データフレーム)でコンソールに結果が出力されます。 # rep_regression(データフレーム, "ファイル名")で,作業フォルダに結果が出力されます(コンソールにも出ます)。 rep_regression <- function(dFrame, outFile = "", sub = 1, fac = 2, x = 3, y = 4) { #被験者ベクトルと水準ベクトルを因子に変換 dFrame[[sub]] <- as.factor(dFrame[[sub]]) dFrame[[fac]] <- as.factor(dFrame[[fac]]) #被験者数,水準数など subLevels <- levels(dFrame[[sub]]) facLevels <- levels(dFrame[[fac]]) nSub <- length(subLevels) nFac <- length(facLevels) #回帰係数用のベクトル regCoef <- c(0) regIntercept <- c(0) #被験者と条件用のベクトル subVec <- c("") condVec <- c("") #データ数 nVec <- c(0) #カウンタ cnt <- 1 for(i in 1:nFac) { for(j in 1:nSub) { #j番目の人のi番目の水準のデータを取り出す subFrame <- dFrame[dFrame[sub] == subLevels[j] & dFrame[fac] == facLevels[i],] #回帰分析 regResult <- lm(subFrame[[y]] ~ subFrame[[x]]) #回帰係数を取り出す regCoef[cnt] <- coef(regResult)[2] #切片を取り出す regIntercept[cnt] <- coef(regResult)[1] subVec[cnt] <- subLevels[j] condVec[cnt] <- facLevels[i] nVec[cnt] <- length(subFrame[[sub]]) cnt <- cnt + 1 } } outFrame <- data.frame(condVec, subVec, regCoef, regIntercept, nVec) names(outFrame) <- c("condition", "subject", "coefficents", "intercept", "n") if(outFile != "") {write.table(outFrame, outFile, quote = FALSE, sep = "\t")} return(outFrame) }