Nad Pat
Nad Pat

Reputation: 3173

Using for loop in lapply

Lets take a 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)
                )

The data is further divided to form a list as,

datsplit =  split(dataset, dataset$env)

I am trying to apply this loop over the list.

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)
    }
  }
}

The above function is looped over the list using lapply.

lapply(datsplit, zz)

But the result is showing NULL. (The result should have been in a matrix form)

$`1`
NULL

$`2`
NULL

$`3`
NULL

Here is an Example when applied to 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

The expected output should be a list of 3 with 5x3 matrix.

Upvotes: 1

Views: 161

Answers (1)

wurli
wurli

Reputation: 2748

Your function zz() doesn't return anything. Try this:

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

Upvotes: 2

Related Questions