如何传递和使用数据框到函数 [英] How to pass and use a data frame to a function

查看:95
本文介绍了如何传递和使用数据框到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我定义的函数中传递和使用数据框。但是我失败了。我想知道如何在R中传递和使用数据框。

I want to pass and use a data frame in a function that I defined. But I failed. I would like to know how to pass and use a data frame in R.

我使用的代码如下:


# create example data

testData <- data.frame(man = c(9, 8, 3, 4, 8),         
                       woman = c(5, 4, 7, 1, 1),
                       love = c(1, 2, 3, 4, 5))


# define the function

polynomial <- function(iv1, iv2, dv, dataset){
  model <- lm(dv ~ iv1 + iv2 + I(iv1^2) + I(iv1 * iv2) + I(iv2^2), data = dataset)
  return(summary(model))
}

# use the function

polynomial(iv1 = man,
           iv2 = woman, 
           dv = love,
           dataset = testData)

但是我收到此错误消息- eval(predvars,data,env)中的错误:找不到对象'love'。有人知道如何解决这个问题吗?

But I got this error message - Error in eval(predvars, data, env) : object 'love' not found. Does anyone know how to solve this?

推荐答案

请尝试以下操作:

polynomial <- function(iv1, iv2, dv, dataset){
  formula <- substitute(dv ~ iv1 + iv2 + I(iv1^2) + I(iv1 * iv2) + I(iv2^2))
  model <- lm(formula = formula, data = dataset)
  return(summary(model))
}

然后您可以根据需要使用它:

You can then use it as you wished :

polynomial(iv1 = man,
           iv2 = woman, 
           dv = love,
           dataset = testData)

替代将替换名称 dv iv1 iv2 以及您在函数调用中提供的参数名称(在本例中为男人女人)。确实,如果在函数中打印对象公式的值,您将得到 love〜男人+女人+ I(man ^ 2)+ I(man *女人)+ I(woman ^ 2)。您还可以咨询相关的 stackoverlock问题 H. Wickham的文章以更好地理解它是如何工作的。

substitute will replace the names dv, iv1, iv2 with the names of the arguments that you provide in your function call (in your case man, woman, love). Indeed, if you print the value of the object formula in your function you will get love ~ man + woman + I(man^2) + I(man * woman) + I(woman^2). You can also consult a related stackoverlock question or the article of H. Wickham to understand better how it works.

这篇关于如何传递和使用数据框到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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