apply does not result in the same vector like replaced for
the function "trio" exemplifies a function with numerous calculations, that takes in certain columns from a data frame (df) and three values for the calculations:
# example: data
df <- data.frame(C1= c(1,2,3,4,5,6),C2= c(5,4,3,2,1,6),C3= c(9,1,5,2,7,4))
# example: function
trio <- function(a,b,c){
df2 <- df %>%
mutate(.,
df$C1 * a,
df$C2 * b,
df$C2 * c
)
df2$calc <- df2[3] * df2[4]/df2[5]
max(df2$calc)
}
to find which value combination results in the best output (= max(df2$calc) a matrix with value combinations is created:
pp <- expand.grid(parameter_A = round(seq(min, max, length.out = count),3),
parameter_B = round(seq(min, max, length.out = count),3),
parameter_C = round(seq(min, max, length.out = count),3))
To replace the for loop
max.all<- c()
for(w in 1:nrow(pp)){
max.all[w] <- findWinZ(pp[w,1],pp[w,2],pp[w,3])
}
I aimed to use one function of the Apply-Family (sapply, lapply), eg
Version1: res2 <- sapply(pp, function(a,b,c) findWinZ(length(pp[,1]),length(pp[,2]),length(pp[,3])))
Version: res3 <- sapply(pp, function(a,b,c) length(findWinZ(pp[w,1],pp[w,2],pp[w,3])))
Alas, the outcome of the apply() loops is wrong. What I need is the vector with all results, ie the same output as I get from the for loop. Please, can anyone correct my apply() code? Thanks a lot!
如果问题是如何将for循环重写为sapply,那么:
res4 <- sapply(1:nrow(pp), function(w) findWinZ(pp[w,1],pp[w,2],pp[w,3]))
链接地址: http://www.djcxy.com/p/38296.html
上一篇: 读取R中的原始数据以使用Dropbox API保存为.RData文件
下一篇: 申请不会导致像替换为相同的载体