Search code examples
rlistfunctionfor-loopvegan

How can I tell R to apply functions to multiple data?


I have been stacking this work for quite long time, tried different approaches but couldn't succeed.

what I want is to apply following 4 functions to 30 different data (data1,2,3,...data30) within for loop or whatsoever in R. These datasets have same (10) column numbers and different rows.

This is the code I wrote for first data (data1). It works well.

for(i in 1:nrow(data1)){
  data1$simp <-diversity(data1$sp, "simpson")
  data1$shan <-diversity(data1$sp, "shannon")
  data1$E <- E(data1$sp)
  data1$D <- D(data1$sp)
}

I want to apply this code for other 29 data in order not to repeat the process 29 times.

Following code what I am trying to do now. But still not right.

data.list <- list(data1, data2,data3,data4,data5)
for(i in data.list){
  data2 <- NULL
  i$simp <-diversity(i$sp, "simpson")
  i$shan <-diversity(i$sp, "shannon")
  i$E <- E(i$sp)
  i$D <- D(i$sp)
  data2 <- rbind(data2, i)
  print(data2)
}

So I wanna ask how I can tell R to apply functions to other 29 data?

Thanks in advance!


Solution

  • You can do this with Map.

    fun <- function(DF){
      for(i in 1:nrow(DF)){
        DF$simp <-diversity(DF$sp, "simpson")
        DF$shan <-diversity(DF$sp, "shannon")
        DF$E <- E(DF$sp)
        DF$D <- D(DF$sp)
      }
      DF
    }
    
    result.list <- Map(fun, data.list)
    

    Or, if you don't want to have a function fun in the .GlobalEnv, with lapply.

    result.list <- lapply(data.list, function(DF){
      for(i in 1:nrow(DF)){
        DF$simp <-diversity(DF$sp, "simpson")
        DF$shan <-diversity(DF$sp, "shannon")
        DF$E <- E(DF$sp)
        DF$D <- D(DF$sp)
      }
      DF
    })