在R中传递和返回函数 [英] Passing and returning functions in 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屋!