簡體   English   中英

在 lapply 中使用 for 循環

[英]Using for loop in lapply

讓我們拿一個 dataframe,

dataset = data.frame(env = c(1:3),
                rep = c(1:3),
                ind1 = c(1:5),
                ind2 = c(6:8),
                dep = rnorm(180, mean = 100, sd=10)
                )

數據被進一步划分以形成一個列表,

datsplit =  split(dataset, dataset$env)

我正在嘗試將此循環應用於列表。

zz = function(x){
  twt <- tapply(x[, 5], x[, 3:4], mean, na.rm = TRUE)
  Means <- twt
  testers <- ncol(twt)
  lines <- nrow(twt)
  SCA <- twt
  for (i in 1:lines) {
    for (j in 1:testers) {
      SCA[i, j] <- twt[i, j] - mean(twt[, j]) - mean(twt[i, ]) + 
                           mean(twt)
    }
  }
}

上面的 function 使用lapply在列表中循環。

lapply(datsplit, zz)

但結果顯示 NULL。 (結果應該是矩陣形式)

$`1`
NULL

$`2`
NULL

$`3`
NULL

這是應用於 dataframe dataset時的示例

twt <- tapply(dataset[, 5], dataset[, 3:4], mean, na.rm = TRUE)
Means <- twt
testers <- ncol(twt)
lines <- nrow(twt)
SCA <- twt
for (i in 1:lines) {
  for (j in 1:testers) {
    SCA[i, j] <- twt[i, j] - mean(twt[, j]) - mean(twt[i, ]) + 
      mean(twt)
  }
}
}

SCA
    ind2
ind1         6         7          8
   1 -3.053776  0.726515  2.3272607
   2 -2.717726  3.549950 -0.8322246
   3  1.014952  1.906804 -2.9217556
   4  3.572287 -4.175673  0.6033861
   5  1.184263 -2.007596  0.8233333

預期的 output 應該是 3 個具有 5x3 矩陣的列表。

您的 function zz()不返回任何內容。 嘗試這個:

zz = function(x){
  twt <- tapply(x[, 5], x[, 3:4], mean, na.rm = TRUE)
  Means <- twt
  testers <- ncol(twt)
  lines <- nrow(twt)
  SCA <- twt
  for (i in 1:lines) {
    for (j in 1:testers) {
      SCA[i, j] <- twt[i, j] - mean(twt[, j]) - mean(twt[i, ]) + 
        mean(twt)
    }
  }
  # Return the SCA object
  SCA
}

lapply(datsplit, zz)
#> $`1`
#>     ind2
#> ind1 6
#>    1 0
#>    2 0
#>    3 0
#>    4 0
#>    5 0
#> 
#> $`2`
#>     ind2
#> ind1 7
#>    1 0
#>    2 0
#>    3 0
#>    4 0
#>    5 0
#> 
#> $`3`
#>     ind2
#> ind1 8
#>    1 0
#>    2 0
#>    3 0
#>    4 0
#>    5 0

暫無
暫無

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

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