[英]use of apply in a function that accepts vector, matrix, or data.frame as an argument
[英]Build a vector of results using a function and argument as data frame
如果有功能,請告知我應該使用哪個功能( map
/ lapply
/ sapply
..):
foo <- function(x, argument1 = "abc", default_score = def_score_dataframe)
returning score
其中x
將是一個數據幀,每次我運行該函數時,argument1將被更改,並且default_score是一個data.frame
,每行中具有: name
, default_score
。
我想要的是使用像map
/ lapply
這樣的lapply
函數,它將采用值向量來分配給argument1並返回帶有argument1_Value
和Score
列的數據框
換句話說,是這樣的:
res_df <- lapply(argument_values,
foo(x, argument1 = argument_values, default_score = def_score_dataframe))
這應該給我以下結果:
res_df
# argument1_Value Score
# "aaa" 5
我將通過一個示例回答您的問題。
您有一個對數據框x
,向量( vectorArgument
)和另一個參數(默認vectorArgument
2的exponent
)進行exponent
myFun = function(x, vectorArgument, exponent = 2){
z = (colSums(x) - vectorArgument) ^ exponent
}
如果將此功能應用於
df = data.frame(A = 1:4, B = 5:8)
d = myFun(df, c(1,22),3)
# You would get:
> d
A B
729 64
現在,您在另一個數據框中有一組vectorArguments
:
argumentsDF = data.frame(arg1 = c(1,22), arg2 = c(3,3), arg3 = c(17,21))
為了在df上計算上述函數,並針對每一列( margin = 2
)作為vectorArgument
參數,請執行以下操作:
result = apply(X = argumentsDF,
MARGIN = 2,
FUN = function(y){
myFun(x = df,
vectorArgument = y,
exponent = 3)
}
)
您將獲得:
> result
arg1 arg2 arg3
A 729 343 -343
B 64 12167 125
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.