R - could I have avoided for loop here?

76 Views Asked by At

I'm an R newbie trying to use an apply function, recommended as good style, but here's I've failed.

I have two data frames - one a collection of records from my bank statements, the other a bunch of records, read in from a database, detailing a regex pattern to apply to one or other column from the statement and assign a value to an account category, sometimes a cross reference.

I had defined a function which applied each regex pattern record to the statement data frame, but using an apply function for each record in the set of patterns only ever operated on the original statement data frame - not the frame as operated on by the application of any previous patterns.

I suspect that this is a case where the operations are inherently in sequence, and so apply functions will never work - but am I missing something? To show exactly what I'm trying to do, below is the code, using a for loop, which did work:

doRegex <- function (df.Statement, df.Patterns) 
{
    m <- as.matrix(df.Patterns)
    for (i in 1:NROW(df.Patterns))
    {
        v <- m[i,]
        rows <- grep(v[2], df.Statement[,v["txtColumn"]], TRUE)
        v["txtAccount"] -> df.Statement[rows,"Account"]
        if (!is.na(v["txtXRef"])) v["txtXRef"] ->  df.Statement[rows,"XRef"]
    }
    return(df.Statement)
}

doRegex(df.recentCSV, df.Patterns) -> df.recentCSV
0

There are 0 best solutions below