找不到对象在函数中出现ddply错误 [英] Object not found error with ddply inside a function

查看:370
本文介绍了找不到对象在函数中出现ddply错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真的挑战了我调试R代码的能力。

我想用 ddply()将相同的函数应用到按顺序命名的不同列;例如。 a,b,c。为此,我打算重复传递列名作为字符串并使用 eval(parse(text = ColName))来允许函数引用它。直到我把 ddply()放入另一个函数内为止, 。以下是示例代码:

 #所需软件包:
库(plyr)

myFunction< - function(x,y){
NewColName =a
z = ddply(x,y,summary,
Ave = mean(eval(parse(text = NewColName)) ,na.rm = TRUE)

return(z)
}

a = c(1,2,3,4)
b = c (0,0,1,1)
c = c(5,6,7,8)
df = data.frame(a,b,c)
sv = c(b )

#This Works。
ColName =a
ddply(df,sv,summary,
Ave = mean(eval(parse(text = ColName)),na.rm = TRUE)


#这不起作用
#Produces错误:解析错误(text = NewColName):找不到对象'NewColName'
myFunction(df,sv)

#两种情况下的输出应该是
#b Ave
#1 0 1.5
#2 1 3.5

有什么想法? NewColName甚至定义在函数内部!



我想过这个问题的答案, loop-to-create-new-variables-in-ddply ,可能对我有帮助,但我今天做了足够的头撞,现在是时候提出我的意见了你可以使用 do.call 的组合来完成这项工作。

code>和调用 NewColName 仍然可见的环境中构建调用:

  myFunction<  -  function(x,y){
NewColName< - a
z< - do .call(ddply,list(x,y,summarize,Ave = call(mean,as.symbol(NewColName),na.rm = TRUE)))
return(z)
}

myFunction(df,sv)
b Ave
1 0 1.5
2 1 3.5


This has really challenged my ability to debug R code.

I want to use ddply() to apply the same functions to different columns that are sequentially named; eg. a, b, c. To do this I intend to repeatedly pass the column name as a string and use the eval(parse(text=ColName)) to allow the function to reference it. I grabbed this technique from another answer.

And this works well, until I put ddply() inside another function. Here is the sample code:

# Required packages:
library(plyr)

myFunction <- function(x, y){
    NewColName = "a"
    z = ddply(x, y, summarize,
            Ave = mean(eval(parse(text=NewColName)), na.rm=TRUE)
    )
    return(z)
}

a = c(1,2,3,4)
b = c(0,0,1,1)
c = c(5,6,7,8)
df = data.frame(a,b,c)
sv = c("b")

#This works.
ColName = "a"
ddply(df, sv, summarize,
        Ave = mean(eval(parse(text=ColName)), na.rm=TRUE)
)

#This doesn't work
#Produces error: "Error in parse(text = NewColName) : object 'NewColName' not found"
myFunction(df,sv)

#Output in both cases should be
#  b Ave
#1 0 1.5
#2 1 3.5

Any ideas? NewColName is even defined inside the function!

I thought the answer to this question, loops-to-create-new-variables-in-ddply, might help me but I've done enough head banging for today and it's time to raise my hand and ask for help.

解决方案

You can do this with a combination of do.call and call to construct the call in an environment where NewColName is still visible:

myFunction <- function(x,y){
NewColName <- "a"
z <- do.call("ddply",list(x, y, summarize, Ave = call("mean",as.symbol(NewColName),na.rm=TRUE)))
return(z)
}

myFunction(d.f,sv)
  b Ave
1 0 1.5
2 1 3.5

这篇关于找不到对象在函数中出现ddply错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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