2012-08-24 42 views
5

在此先感謝,並對不起,如果這個問題已被回答以前 - 我已經看得相當廣泛。我有一個數據集包含一連串的信息,特別是:名稱,顏色代碼,一些函數表達式。例如,一個值可能是:創建一個字符向量的函數列表

成本#FF0033 @ log(x)+6。

我有所有的代碼來提取信息,最後我得到了一個我想轉換爲實際函數列表的向量表達式。

例如:

func.list <- list() 
test.func <- c("x","x+1","x+2","x+3","x+4") 

其中test.func是表達式的矢量。我想的是:

func.list[[3]] 

等同於

function(x){x+3} 

我知道我可以使用創建一個函數:

somefunc <- function(x){eval(parse(text="x+1"))} 

爲一個字符值轉換成一個功能。當我嘗試循環制作多個功能時,問題就出現了。對於東西,我試過一個例子,沒有工作:

for(i in 1:length(test.func)){ 
    temp <- test.func[i] 
    f <- assign(function(x){eval(expr=parse(text=temp))}) 
    func.list[[i]] <- f 
} 

基於另一篇文章(http://stats.stackexchange.com/questions/3836/how-to-create-a-vector-of -functions)我也試過這樣:

makefunc <- function(y){y;function(x){y}} 
for(i in 1:length(test.func)){ 
    func.list[[i]] <- assign(x=paste("f",i,sep=""),value=makefunc(eval(parse(text=test.func[i])))) 
} 

其中提供了以下錯誤:錯誤的eval(表達式,ENVIR,enclos):對象 'X' 未找到

最終目標是把清單並將第j個函數應用於data.frame的第j列,以便腳本的用戶可以指定如何規範化每個列在由列標題給出的連接信息內。

回答

3

也許有一個通用的函數初始化列表,然後利用更新它們:

foo <- function(x){x+3} 
> body(foo) <- quote(x+4) 
> foo 
function (x) 
x + 4 

更具體地講,從一個字符開始,你可能會做這樣的事情:

body(foo) <- parse(text = "x+5") 
+0

謝謝!它工作完美。一旦SO允許我這樣做,我將添加用於完成該任務的代碼作爲其他用戶的附加答案。 (並且對所有的評論/編輯/刪除/以及whatnot感到抱歉 - 我明顯是新來的SO) – dayne

+0

@dayne我想說,與一般的全新SO訪問者相比,你已經掌握了一切事情。 – joran

2

只是爲了增加喬蘭的回答,這是最後的工作:

test.data <- matrix(data=rep(1,25),5,5) 
test.data <- data.frame(test.data) 

test.func <- c("x","x+1","x+2","x+3","x+4") 
func.list <- list() 

for(i in 1:length(test.func)){ 
    func.list[[i]] <- function(x){} 
    body(func.list[[i]]) <- parse(text=test.func[i]) 
} 

processed <- mapply(do.call,func.list,lapply(test.data,list)) 

Thanks aga在,喬蘭。

1

這是我做的:

f <- list(identity="x",plus1 = "x+1", square= "x^2") 
funCreator <- function(snippet){ 
    txt <- snippet 
    function(x){ 
    exprs <- parse(text = txt) 
    eval(exprs) 
    } 
} 
listOfFunctions <- lapply(setNames(f,names(f)),function(x){funCreator(x)}) # I like to have some control of the names of the functions 
listOfFunctions[[1]] # try to see what the actual function looks like? 
library(pryr) 
unenclose(listOfFunctions[[3]]) # good way to see the actual function http://adv-r.had.co.nz/Functional-programming.html 
# Call your funcions 
listOfFunctions[[2]](3) # 3+1 = 4 
do.call(listOfFunctions[[3]],list(3)) # 3^2 = 9 
attach(listOfFunctions) # you can also attach your list of functions and call them by name 
square(3) # 3^2 = 9 
identity(7) # 7 ## masked object identity, better detach it now! 
detach(listOfFunctions) 
相關問題