简体   繁体   English

在数据框中应用功能列列表

[英]applying list of functions columns in data frame

I have 2 variables, a and b . 我有2个变量, ab a is potentially very large. a可能非常大。 b is always a vector of functions that can be applied to each column in the data frame a . b始终是可以应用于数据帧a每一列的函数的向量。

a <- data.frame(col1=c(1, 2, 3), col2=c(4, 5, 6))
b <- c(as.double, function(x) {1+x})

So the result that I want is that function b[1] is applied to col1, b[2] is applied to col2, and so on for all columns. 所以我想要的结果是将函数b[1]应用于col1,将b[2]应用于col2,以此类推。 I feel lapply should be used here but documentation seems to say that it can only have one function. 我觉得应该在这里使用lapply,但是文档似乎说它只能有一个功能。 I could use a loop I suppose but a "vectorised" way would be nice. 我可以使用我想使用的循环,但是采用“向量化”的方式会更好。

This is one way to do it: 这是一种方法:

results <- mapply(function(i,j) b[[i]](a[[j]]), i=1:length(b), j=1:length(a)) 

It gives you: 它为您提供:

> results
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    3    7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM