问题
How do I run the following piece of code that the output of function ftn4 using values from data frame I, is used by the newtonraphson function in combination with values from data frame R0. I would like to store the output in a new data frame (R) of the same dimensions (ncol = 5, nrow = 5) as I an R0.
I am stuck, any ideas? Any hint greatly appreciated
c = c(0.3)
Ccf = c(0.3)
Acf = c(3*10^-6)
E = c(0.00006)
Ke = c(1000)
I = as.data.frame(matrix(sample(seq(150,300,0.1),25), ncol = 5, nrow = 5))
R0 = as.data.frame(matrix(sample(seq(0.01,0.2,0.001),25), ncol = 5, nrow = 5))
library(spuRs)
ftn4 <- function(x) {
f = { x^2*exp(c*x)- (Ccf*Acf*E*(I/Ke+I))}
f1 = { 2 * x * exp(c * x) + x^2 * (exp(c * x) * c)}
return(c(f,f1))
}
R = as.data.frame(newtonraphson(ftn4, R0, tol = 1e-09 ,max.iter = 1000))
回答1:
As appointed by the comments, you should pass arguments to the function ftn4 that yields to a value. So ftn4, should be changed by:
ftn4 <- function(x,I) {
f = { x^2*exp(c*x)- (Ccf*Acf*E*(I/Ke+I))}
f1 = { 2 * x * exp(c * x) + x^2 * (exp(c * x) * c)}
return(c(f,f1))
}
And now iterate over your matrix I and R0.
R <- data.frame(matrix(NA,nrow=nrow(I), ncol(I)))
for(i in 1:nrow(I)){
for(j in 1:ncol(I)){
R[i,j] <- newtonraphson(ftn = function(x) ftn4(x, I[i,j]),
x0 = R0[i,j],
tol = 1e-09,
max.iter = 1000)
}
}
来源:https://stackoverflow.com/questions/32167058/use-values-from-different-dataframes-as-input-for-nested-function