簡體   English   中英

R:用apply函數替換for循環

[英]R: Replacing a for-loop with an apply function

我設法對數據框的每個主題應用線性回歸,並使用for循環將值粘貼到新的數據框中。 但是,我認為應該使用apply函數獲得更易讀的結果,但是我的所有嘗試都失敗了。 這是我的方法:

numberOfFiles <- length(resultsHick$subject)
intslop       <- data.frame(matrix(0,numberOfFiles,4))
intslop       <- rename(intslop,
                        subject   = X1,
                        intercept = X2,
                        slope     = X3,
                        Rsquare   = X4)

cond        <- c(0:3)
allSubjects <- resultsHick$subject

for (i in allSubjects)
    {intslop[i,1] <- i

     yvalues <- t(subset(resultsHick,
                  subject == i, 
                  select = c(H0meanRT, H1meanRT, H2meanRT, H258meanRT)))

     fit        <- lm(yvalues ~ cond)
     intercept  <- fit$coefficients[1]
     slope      <- fit$coefficients[2]
     rsquared   <- summary(fit)$r.squared
     intslop[i,2] <- intercept
     intslop[i,3] <- slope
     intslop[i,4] <- rsquared
     }

結果應與以下內容相同

> head(intslop)
  subject intercept    slope   Rsquare
1       1  221.3555 54.98290 0.9871209
2       2  259.4947 66.33344 0.9781499
3       3  227.8693 47.28699 0.9537868
4       4  257.7355 80.71935 0.9729132
5       5  197.4659 49.57882 0.9730409
6       6  339.1649 61.63161 0.8213179
...

有人知道使用apply函數編寫此代碼的方法更易讀嗎?

我用來替換匯總data.frames的循環的一種常見模式是:

do.call(
  rbind,
  lapply(1:numberOfDataFrames,
         FUN = function(i) {
           print(paste("Processing index:", i)) # helpful to see how slow/fast
           temp_df <- do_some_work[i]
           temp_df$intercept <- 1, etc.
           return(temp_df) # key is to return a data.frame for each index.
         }
  )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM