2013-10-17 29 views
1

我想用一个函数在R中写一个函数来同时绘制一个图。我的函数调用多个参数,包括一个FUN参数,该参数指定每个样本应该使用哪个绘图函数。如何在R中使用不同参数运行一个函数?

我想读取表/数据帧到R中,然后在每行上运行相同的函数,其中每行指定该运行的参数。

我的功能看起来是这样的:

printTiff <- function(FUN, sample, start, end) { 
    tiff(paste(sample,".tiff", sep=""), compression="lzw",width=892,height=495) 
    g <- FUN(sample,start,end) 
    dev.off() 
} 

我有一个表的乐趣,样品,开始和结束列,每一行应该结束了一个不同的口角。我试过使用do.call,但我似乎无法正确使用它。我有几百个样本,所以我想避免每次运行都改变参数。

样品表:

 FUN  sample start  end 
1 T7Plots sample343 27520508 27599746 
2 C9Plots sample347 27522870 27565523 
3 C9Plots sample345 27535342 27570585 

回答

2

可以使用match.fun通过其名称来查找功能,那么你可以使用它。

printTiff <- function(FUN, sample, start, end) { 
    FUN <- match.fun(FUN) 
    paste(sample, FUN(start), end); 
} 

table <- read.table(header=TRUE, stringsAsFactors=FALSE, text=" 
FUN  sample start  end 
T7Plots sample343 27520508 27599746 
C9Plots sample347 27522870 27565523 
C9Plots sample345 27535342 27570585 
") 


T7Plots <- `-` 
C9Plots <- function(x) 1/x 

然后我们就可以mapply使用像@alexis_laz

mapply(printTiff, table[,1], table[,2], table[,3] ,table[,4]) 
+0

我不会使用'get'来匹配一个函数。使用'明确*为此设计的'match.fun'函数。 –

+0

@ SimonO101更新的答案使用match.fun –

3

使用mapply

mapply(printTiff, table[,1], table[,2], table[,3] ,table[,4]) 
+0

我试图mapply使用如你所说,但它不会读的第一列作为函数名。它不断返回'test [,1]'是不是一个函数,字符或符号的任何想法? – user2892231

相关问题