0

I'm working on a data table structure and I want to create a new column based on the call of a function that uses an existing data table column. Here's my current code:

`for(i in 1:nbNewColumns)
    {
        existingColumn <- paste0("W", toString(i))
        newColumnName <- paste0("ID", toString(i))
        myDT[, (newColumnName) := MyFunction(param1, eval(existingColumn))]
    }`   

My existing columns are W1, W2, ..., Wn (words)
My new columns are ID1, ID2, ..., IDn. (words id)
This code doesn't generate an error but the 2nd parameter of myFunction is the column name, not the column value.
I tested lot of different syntaxes based on eval, quote, DT[[]], ... but nothing works, I'm unable to send the column value to myFunction.
If I replace the function call by a constant, it works.

[Update] The issue is related to the type of the 2nd parameter of myFunction:

myFunction <- function(pWordsTable, pWord)
    {
        return(pWordsTable[word == pWord,]$wordId)
    }

The 2nd parameter of the function is normally a string (a word) but the result of the get(existingColumn) is a list, so I get an error message:
Error in [.data.table (pWordsTable, word == pWord, ) : RHS of == is length 3 which is not 1 or nrow (31248). For robustness, no recycling is allowed (other than of length 1 RHS). Consider %in% instead.

[Update 2]
I defined a dedicated function to process list of words and it works fine.
Thank's for your help.

Dan82
  • 41
  • 8

0 Answers0