【发布时间】:2017-06-19 22:35:44
【问题描述】:
我有 2 个文件。
“增量.tab”
grp increment
1 10
2 25
3 35
4 50
“input.tab”
grp pos
1 10
1 14
1 25
2 3
2 20
3 2
3 10
我正在尝试将增量应用到“input.tab”的第 2 列,例如:
if grp=1, then increment=0
if grp=2, then increment=10
if grp=3, then increment=10+25=35
if grp=4, then increment=10+25+35=70
...
为了得到这个输出:
grp pos pos_adj
1 10 10
1 14 14
1 25 25
2 3 13
2 20 30
3 2 37
3 10 45
我的计划是使用apply逐行处理输入文件:
ref <- read.table("increment.tab", header=T, sep="\t")
input <- read.table("input.tab", header=T, sep="\t")
my_fun <- function(x, y){
if(x==1){
inc=0
}
else{
inc=sum(ref[1:match(x, ref$grp)-1,2])
}
result = y + inc
return(result)
}
input$pos_adj = apply(input, 1, my_fun(input$grp, input$pos))
但是我收到了这个我无法理解的错误信息。
Error in match.fun(FUN) :
'my_fun(input$grp, input$pos)' is not a function, character or symbol
In addition: Warning message:
In if (x == 1) { :
the condition has length > 1 and only the first element will be used
为什么 'my_fun' 不被视为函数?
【问题讨论】: