DoeyFoey DoeyFoey - 2 months ago 10
R Question

R: Including a loop within a function?

Following code can be used to create a data.frame with Kendall-Tau and Spearman correlation results next to each other:

data(mtcars)
mtcars

correlation <- function(x,y){
df1 = cor(data.frame(x,y), use="complete.obs", method="kendall")
df2 = cor(data.frame(x,y), use="complete.obs", method="spearman")
return(data.frame(df1,df2))
}

correlation(mtcars[1],mtcars[2])


Question: Instead of chaining the commands, could something like a loop for the two method be implemented?

methods <- ("kendall", "spearman")

correlation <- function(x,y){
df = cor(data.frame(x,y), use="complete.obs", method=methods)
return(data.frame(df))
}

correlation(mtcars[1],mtcars[2])
#This should output the two results, just as above.


I tried a list but wasn't successful with that.

Answer

You could use a for statement. Just do the following:

methods <- c("kendall", "spearman")

    correlation <- function(x,y, methods){

      result <- list()
      for (type in methods){

        df = cor(data.frame(x,y), use="complete.obs", method=type)

        result[type] <- list(df)
      }

      return(data.frame(result) )
    }

    correlation(mtcars[1],mtcars[2],methods)