neves
neves

Reputation: 846

Why lapply works and apply doesn't?

My data:

 df_1 <- data.frame(
      x = replicate(
        n = 3, 
        expr = runif(n = 30, min = 20, max = 100)
      ), 
      y = sample(
        x = 1:3, size = 30, replace = TRUE
      )
    )

The follow code with lapply works:

lapply(X = names(df_1)[c(1:3)], FUN = function(x) {
  pairwise.t.test(
    x = df_1[, x], 
    g = df_1[['y']], 
    p.adj = 'bonferroni'
  )
})

But, with apply doesn't:

apply(X = names(df_1)[c(1:3)], MARGIN = 2, FUN = function(x) {
  pairwise.t.test(
    x = df_1[, x], 
    g = df_1[['y']], 
    p.adj = 'bonferroni'
  )
})

Error in apply(X = names(df_1)[c(1:3)], MARGIN = 2, FUN = function(x) { : dim(X) must have a positive length

Why the problem? Are they not equivalent?

Upvotes: 0

Views: 47

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

For apply you should instead use

apply(X = df_1[1:3], MARGIN = 2, FUN = function(x) {
    pairwise.t.test(
    x = x, 
    g = df_1[['y']], 
    p.adj = 'bonferroni'
 )
})

that is because from ?apply

apply returns a vector if MARGIN has length 1 and an array of dimension dim(X)[MARGIN] otherwise.

In your attempt you are using names(df_1)[c(1:3)] as argument to apply which has

dim(names(df_1)[c(1:3)])[2]
#NULL

Hence, you get the error.

Upvotes: 1

Related Questions