R:在函数中包含一个循环?

时间:2016-10-10 07:23:00

标签: r function foreach

以下代码可用于创建一个数据框架,其中Kendall-Tau和Spearman相关结果彼此相邻:

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])

问题:不是将命令链接起来,而是可以实现两种方法的循环吗?

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.

我尝试了一个列表,但没有成功。

1 个答案:

答案 0 :(得分:0)

# 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))

结果:

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

谢谢!