R:在函数中包含循环吗? [英] R: Including a loop within a function?

查看:69
本文介绍了R:在函数中包含循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可用于创建具有Kendall-Tau和Spearman相关结果彼此相邻的data.frame:

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.

推荐答案

您可以使用for语句. 只需执行以下操作:

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)

这篇关于R:在函数中包含循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆