在R中传递和返回函数 [英] Passing and returning functions in R

查看:181
本文介绍了在R中传递和返回函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中创建一个函数,它将数据作为一个函数,对它进行一些操作(添加一些列/行等)并返回。我发现通常我不能这样做。

  f < -  function(d = cars){
d $ new = ifelse(d $ dist> rep (10,nrow(d)),1,0)
return d
}

错误:意外符号:
d $ new = ifelse $ dist> rep(10,nrow(d)),1,0)
return d

如果我删除返回d,我只得到向量,而不是整个数据框。

任何建议?

解决方案

R中的函数返回执行的最后一个语句的值。执行作业时,赋值左侧的值是(隐形)返回的结果。对于例子

  d<  -  cars 
a < - (d $ new< - ifelse(d $ dist> ; 10,1,0))
a

#[1] 0 0 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
#[40] 1 1 1 1 1 1 1 1 1 1 1

所以在你的例子中,你只是返回刚创建的向量。 R不知道你想要返回整个 d data.frame。如果你把 return(d),它会知道你想要的。您甚至可以在最后一行自行放置 d 以返回该值。


I want to create a function in R, which take data as a function, do some operation on it(add some columns/Rows etc) and return it. I found usually I can not do so.

f <- function(d = cars){
    d$new = ifelse(d$dist > rep(10, nrow(d)), 1, 0)
    return d 
}

Error: unexpected symbol in:
"d$new= ifelse(d$dist>rep(10,nrow(d)),1,0)
return d"

If I remove return d, I get only the vector, not whole data frame.
Any suggestion?

解决方案

Functions in R return the value from the last statement executed. When you do an assignment, the value from the left side of the assignment is the (invisibly) returned result. For exampel

d <- cars
a <- (d$new <- ifelse(d$dist>10, 1, 0))
a

#  [1] 0 0 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
# [40] 1 1 1 1 1 1 1 1 1 1 1

So in your example you're merely returning the vector you just created. R doesn't know that you want to return the whole d data.frame. If you put the return(d), it will know that's what you want. You can even just put d on the last line by itself to return that value.

这篇关于在R中传递和返回函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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