rlapplyliterate-programming

R: iterate a function over two lists simultaneously using lapply?


I have multiple factors dividing my data.

By one factor (uniqueGroup), I would like to subset my data, by another factor (distance), I want to first classify my data by "moving threshold", and then test statistical difference between groups.

I have created a function movThreshold to classify my data, and test it by wilcox.test. To vary the different threshold values, I just run

lapply(th.list,       # list of thresholds
       movThreshold,  # my function
       tab = tab,     # original data
       dependent = "infGrad") # dependent variable

Now I've realized, that in fact I need to firstly subset my data by uniqueGroup, and then vary the threshold value. But I am not sure, how to write it in my lapply code?


My dummy data:

set.seed(10)
infGrad <- c(rnorm(20, mean=14, sd=8),
            rnorm(20, mean=13, sd=5),
            rnorm(20, mean=8, sd=2),
            rnorm(20, mean=7, sd=1))
distance <- rep(c(1:4), each = 20)
uniqueGroup <- rep(c("x", "y"), 40)

tab<-data.frame(infGrad, distance, uniqueGroup)


# Create moving threshold function &
# test for original data
# ============================================

movThreshold <- function(th, tab, dependent, ...) {

  # Classify data 
  tab$group<- ifelse(tab$distance < th, "a", "b")

  # Calculate wincoxon test - as I have only two groups
  test<-wilcox.test(tab[[dependent]] ~ as.factor(group),  # specify column name
                    data = tab)

  # Put results in a vector 
  c(th, unique(tab$uniqueGroup), dependent, uniqueGroup, round(test$p.value, 3))

}

# Define two vectors to run through
# unique group
gr.list<-unique(tab$uniqueGroup)

# unique threshold
th.list<-c(2,3,4)

How to run lapply over two lists??

lapply(c(th.list,gr.list),  # iterate over two vectors, DOES not work!!
              movThreshold, 
              tab = tab, 
              dependent = "infGrad")

In my previous question (Kruskal-Wallis test: create lapply function to subset data.frame?), I've learnt how to iterate through individual subsets within a table:

lapply(split(tab, df$uniqueGroup), movThreshold})

But how to iterate through subsets, and through thresholds at once?


Solution

  • If I understood correctly what you're trying to do, here is a data.table solution:

    library(data.table)
    setDT(tab)[, lapply(th.list, movThreshold, tab = tab, dependent = "infGrad"), by = uniqueGroup]
    

    Also, you can just do a nested lapply.

    lapply(gr.list, function(z) lapply(th.list, movThreshold, tab = tab[uniqueGroup == z, ], dependent = "infGrad"))
    

    I apologize, If I misunderstood what you're trying to do.