DoeyFoey
DoeyFoey

Reputation: 33

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.

Upvotes: 2

Views: 10649

Answers (2)

Indi
Indi

Reputation: 1449

# vector that has your methods
methods <- c("kendall", "spearman")

# function which loops thru the vector of functions
correlation <- function(x,y) {
    a <- lapply(X = methods, FUN = function(m,x,y){
    df1 = cor(data.frame(x,y), use="complete.obs", method= m) 
  },x=x,y=y)

  return(a)
}

res <- correlation(mtcars[1],mtcars[2])
#list to dataframe 

do.call("cbind", lapply(res, as.data.frame))

The results :

           mpg        cyl        mpg        cyl
mpg  1.0000000 -0.7953134  1.0000000 -0.9108013
cyl -0.7953134  1.0000000 -0.9108013  1.0000000

Thanks!

Upvotes: 0

Benjamin Mohn
Benjamin Mohn

Reputation: 301

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)

Upvotes: 1

Related Questions