R将不同的功能应用于不同的数据帧列 [英] R Applying different functions to different data frame columns
问题描述
我将有各种数据框架,我希望定义一些基本功能,然后应用这些功能到数据帧中的各个列。结果将是一个与原始数据帧具有相同行数和列数的数据框。
我希望这个解决方案可以重复使用,不同的功能组合可以应用于不同的数据框架。
用文字解释一下有点棘手。我希望下面的代码可以使上述更清楚。
#构建示例数据框
v_a< ; - c(1,4,8,10,12)
v_b <-C(4,6,7,4,3)
v_c< - c(10,23,45,
v_d < - c(12,45,7,10,5)
df< - data.frame(a = v_a,b = v_b,c = v_c,d = v_d)
#定义一些示例函数
fn_1< - function(x)x * 3
fn_2 < - function(x)x * 4
#将函数集合到向量
vct_functions< - c(fn_1,fn_2,fn_1,fn_1)
#将函数向量应用于列在一个data.frame
new_df< - fn_apply_functionList(df,vct_functions)
我是希望重用上面的解决方案,以便将不同的功能组合应用于相同或不同的数据框架。
再次,以下是一个代码片段这个更清楚。
#创建另一个函数向量
vct_fun ctionsB
#将函数向量应用于data.frame中的列
new_df< - fn_apply_functionList(another_df,vct_functions)
优雅的解决方案的任何想法都将非常受赞赏。
@geotheory几乎在那里, vct_functionsB
强制为列表
尝试这个,
do.call(cbind,lapply (1:ncol(df),函数(c)vct_functions [[c]](df [,c])))
I am trying to develop a reusable solution to the following problem.
I will have various data frames and I wish to define some basic functions and then apply these functions to the various columns in the data frame. The result would be a data frame that has the same number of rows and columns as the original data frame.
I want this solution to be reusable insofar that different combinations of functions can be applied to different data frames.
Its a bit tricky to explain this in words. I am hoping the code below will make the above a bit clearer.
# 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)
I am hoping to reuse the solution above such that a different combination of functions could be applied to the same or a different data frame.
Again, the following is a code snippet to make this clearer.
# 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)
Any ideas on an elegant solution would be really appreciated.
@geotheory was almost there, vct_functionsB
is coerced to a list
Try this,
do.call(cbind, lapply(1:ncol(df), function(c) vct_functions[[c]](df[, c])))
这篇关于R将不同的功能应用于不同的数据帧列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!