我正在尝试为以下问题开发可重用的解决方案。R将不同的功能应用于不同的数据帧列
我将拥有各种数据框,我希望定义一些基本功能,然后将这些功能应用于数据框中的各个列。结果将是与原始数据帧具有相同行数和列数的数据帧。
我希望此解决方案可重复使用,因为可以将不同的功能组合应用于不同的数据帧。
用文字解释这一点有点棘手。我希望下面的代码能够让上述更清晰。
# construct an example data frame
v_a <- c(1, 4, 8, 10, 12)
v_b <- c(4, 6, 7, 4, 3)
v_c <- c(10, 23, 45, 12, 45)
v_d <- c(12, 45, 7, 10, 5)
df <- data.frame(a = v_a, b = v_b, c = v_c, d = v_d)
# define some example functions
fn_1 <- function(x) x * 3
fn_2 <- function(x) x * 4
# assemble functions into a vector
vct_functions <- c(fn_1, fn_2, fn_1, fn_1)
# apply vector of functions to columns in a data.frame
new_df <- fn_apply_functionList(df, vct_functions)
我希望能重复使用以上这样的解决方案,它的功能的不同组合可以被应用到相同的或不同的数据帧。
再次,下面是一个代码片段,使这个更清晰。
# create another vector of functions
vct_functionsB <- c(fn_3, fn_4, fn_1, fn_2)
# apply vector of functions to columns in a data.frame
new_df <- fn_apply_functionList(another_df, vct_functions)
任何关于优雅的解决方案的想法将非常感激。
如果你有2+例如,使用'Map'或'mapply' - 'df [] < - Map(函数(d,f)f(d),df,vct_functions)'来循环相同长度的对象。 – thelatemail
谢谢。我认为Map()解决方案将两组参数传递给一个函数。我想将n个函数的向量应用于n个列表。 – markthekoala