I have 2 matrices and 1 vector with which I intend to substitute them into a function fun
accepting 3 variables. But I don't know how to get my goal.
The 2 matrices both have 5 columns and the single vector has 5 elements. I intent to run the function row by row and the Nth elements of each row and the Nth element of the vector could be used. the first matrix eta
is:
eta.1 eta.2 eta.3 eta.4 eta.5
1.103990 1.345141 1.671156 2.041531 2.435917
1.031078 1.109853 1.229888 1.380356 1.552349
1.018405 1.065593 1.139852 1.236245 1.349988
1.013136 1.046822 1.100638 1.171764 1.257230
1.010249 1.036439 1.078646 1.135048 1.203625
1.008425 1.029847 1.064566 1.111308 1.168612
1.007169 1.025289 1.054776 1.094688 1.143918
the second matrix fn
is:
f.1 f.2 f.3 f.4 f.5
6.27530 15.29211 28.49757 46.41790 69.23123
10.96466 23.60472 39.23650 58.71576 82.53972
14.17965 29.67335 47.61181 68.85091 93.98208
16.78984 34.69621 54.71981 77.67461 104.17505
19.04558 39.07866 61.00511 85.59340 113.45587
21.06106 43.01689 66.70069 92.83912 122.03283
22.89981 46.62361 71.94674 99.55885 130.04526
the vector n
is
1 2 3 4 5
As the function runs, the input element are used like:
fun(1.103990, 6.27530,1)
fun(1.345141, 15.29211,2)
...
fun(1.031078,10.96466,1)
fun(1.109853,23.60472,2)
I hope apply fun
to these 3 lists in one step in some form like:
xxx( fun, eta, fn, n)
?mapply
may be helpful. Does this work for you?
Below fun
is a function that accepts three arguments.
x1 <- read.table(
text = ' 1.103990 1.345141 1.671156 2.041531 2.435917
1.031078 1.109853 1.229888 1.380356 1.552349
1.018405 1.065593 1.139852 1.236245 1.349988
1.013136 1.046822 1.100638 1.171764 1.257230
1.010249 1.036439 1.078646 1.135048 1.203625
1.008425 1.029847 1.064566 1.111308 1.168612
1.007169 1.025289 1.054776 1.094688 1.143918'
)
x2 <- read.table(
text = ' 6.27530 15.29211 28.49757 46.41790 69.23123
10.96466 23.60472 39.23650 58.71576 82.53972
14.17965 29.67335 47.61181 68.85091 93.98208
16.78984 34.69621 54.71981 77.67461 104.17505
19.04558 39.07866 61.00511 85.59340 113.45587
21.06106 43.01689 66.70069 92.83912 122.03283
22.89981 46.62361 71.94674 99.55885 130.04526'
)
x1 <- t(x1) # Expensive operation in case of large data.frames
x2 <- t(x2) # Expensive operation in case of large data.frames
x3 <- 1:5
fun <- function(x1, x2, x3) {
sqrt(x1**2 + x2**2 + x3**2)
}
mapply(fun, x1, x2, x3)
[1] 6.449665 15.480892 28.703732 46.634636 69.454279 11.058340 23.715282 39.370237 58.868038 82.705593 14.251302 29.759758
[13] 47.719846 68.978084 94.124672 16.850079 34.769568 54.813037 77.786362 104.302549 19.098553 39.143529 61.088353 85.694332
[25] 113.572370 21.108888 43.075671 66.776608 92.931896 122.140809 22.943751 46.677749 72.016984 99.645185 130.146372
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.