Search code examples
rfunctionerror-checking

trouble setting default values in a function[r]


Info:

  • I am working in R with the state information package "state.x77"

Goal:

  • I am finding correlations between the independent variables and the dependent "Life expectancy".

Issue with code:

  • I want to set a default value for the method. the below code works just fine. But, of course I can't use the "spearman" or "kendall" methods.
cor_v1_v2 = function(v1, v2 = state.x77[,"Life Exp"], method = "pearson"){
  cor(v1,v2,method = "pearson")
}

I have tried several variants such as:

cor_v1_v2 = function(v1, v2 = state.x77[,"Life Exp"], method = "input"){
  cor(v1,v2,method = "input")
}

and:

cor_v1_v2 = function(v1, v2 = state.x77[,"Life Exp"], method = "pearson"){
  cor(v1,v2,method)
}

I get return use errors for each. I know it's just my syntax and my thinking but I'm still stuck.


Solution

  • I think you just want

    cor_v1_v2 = function(v1, v2 = state.x77[,"Life Exp"], method = "pearson"){
      cor(v1, v2, method = method)
    }
    

    This will default to "pearson" but is changeable to whatever you want.