rdataframetransformuser-defined-functionsflexibility

Within a given dataframe row in R, I want to identify a user-defined function in one cell then apply to adjacent cell


I'm trying to write some code that refers to a data frame column containing user-defined functions, and applies that function to an adjacent column containing raw data.

Specifically, I want to apply the user-defined function stored in column A and apply it to column C for a given row.

Example:


#Create user-defined functions
TF_01 <- function(x) { return (x^2)}
TF_02 <- function(x) { return (x^3)}
    
#Create a, b, c variables
A <- c("8_FAM","8_FAM","8_FAM","8_FAM","13_FAM","13_FAM","13_FAM","13_FAM")
B <- c(TF_01,TF_01,TF_01,TF_01,TF_02,TF_02,TF_02,TF_02)
C <- c(32.2,31.9,32.8,31.6,32.9,34.6,32.7,32.4)
    
#Join variables as data frame
df <- data.frame (A,B,C)

I'm able to hard-code a specific function as but I need flexibility to apply any user-defined function.


Solution

  • Your columnB is not a function column but rather a column containing names for the functions you need. consider using match.fun to be able to call these functions:

    transform(df, D = mapply(\(x, y)match.fun(x)(y), B, C))
    
           A     B    C        D
    1  8_FAM TF_01 32.2  1036.84
    2  8_FAM TF_01 31.9  1017.61
    3  8_FAM TF_01 32.8  1075.84
    4  8_FAM TF_01 31.6   998.56
    5 13_FAM TF_02 32.9 35611.29
    6 13_FAM TF_02 34.6 41421.74
    7 13_FAM TF_02 32.7 34965.78
    8 13_FAM TF_02 32.4 34012.22
    

    cbind(df, D = mapply(\(x,y)x(y), mget(df$B), df$C))