Ich habe 2 Dateien.R: benutzerdefinierte Funktionsproblem mit anwenden
"increment.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
Ich versuche, ein Zuwachs zu Spalte 2 der 'input.tab' anzuwenden, wie zum Beispiel folgende:
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
...
, um diese Ausgabe zu erhalten:
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
Mein Plan ist apply
zu verwenden, um die Eingabedatei Zeile für Zeile zu verarbeiten:
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))
Aber ich bekomme diese Fehlermeldung, die ich nicht wirklich verstehen kann.
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
Warum 'my_fun' wird nicht als eine Funktion betrachtet?
Danke P Lapointe! Funktioniert gut mit dplyr – user31888