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.

2

There are 2 best solutions below

2
On BEST ANSWER

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))

0
On

In base R you can create a new column as a function of an existing column like this:

mtcars$new <- sqrt(mtcars$mpg)
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb      new
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 4.582576
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 4.582576
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 4.774935
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 4.626013
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 4.324350
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 4.254409