Search code examples
rfunctiondatatablesapply

Looping a functions based on elements of a list


I am having some trouble trying to loop a function based on a list and creating a table of results.

head(Dat17_18.3[,c(1,3:5)])
                     Program Area I.E.ScoreStat I.I.ScoreStat I.P.ScoreStat
1             BFA - Art Education             2             2             2
2 BA - Foreign Language Education             2             2             3
3      MAT - Elementary Education             2             2             2
4            BA - Dance Education             2             3             3
5      MAT - Elementary Education             2             3             3
6      MAT - Elementary Education             2             2             3

I have used the split function to create a list of program areas.

test1<- split(Dat17_18.3, Dat17_18.3$`Program Area`)

I wrote a function to extract elements from a from the alpha function in the psych package.

alpha_fun <- function (df,columns){
  library(psych)
  a1 <- alpha(df[,columns])
  a2 <- alpha.ci(a1[[1]][1],nrow(df),length(columns))
  vec1 <- c(nrow(x),a1[[1]][1],a2[1],a2[3],a1[[1]][3])
  return(vec1)
}

I want to have the alpha_fun run for each element in the Test one to create a table for all of the program areas at once.


Solution

  • Consider by (object-oriented wrapper to tapply) which is akin to split + lapply where a function can be directly applied to each subset of data frame grouping. Also, avoid the need for the columns parameter which can be retrieved from data frame input inside the method:

    library(psych)
    
    alpha_fun <- function (df){   
      sub <- df[, 3:ncol(df)]              # KEEP ONLY NUMERIC COLS
    
      a1 <- alpha(sub)
      a2 <- alpha.ci(a1[[1]][1], nrow(sub), ncol(sub))
      vec1 <- c(nrow(sub), a1[[1]][1], a2[1], a2[3], a1[[1]][3])
    
      return(vec1)
    }
    
    # LIST OF VECTORS 
    alpha_vec_list <- by(Dat17_18.3, Dat17_18.3$`Program Area`, alpha_fun)
    
    # MATRIX WITH Program Area AS ROW NAMES
    alpha_mat <- do.call(rbind, alpha_vec_list)