0

I have a equation to solve with uniroot.all, with a dataframe as input parameters.

the dataframe is as followed:

   T  L        f
1  0 10  6.59710
2  0 10  8.01847
3  0 10  9.21858
4  0 10 10.27676
5  0 10 11.23392
6  0 10 12.1144

and the equation to be input to uniroot.all is like:

eqnt <- function(T,l,f)
{    
   T^2 + T*l - f^2
}

sapply(???, uniroot.all(eqnt, ??? ))

How could I make the dataframe as input with apply family function to uniroot.all so that the equation could be solved without using loop structure?

dawei
  • 57
  • 1
  • 7
  • If I understand you correctly you want to make an apply over rows of the data.frame, which was answered here: [mapping over the rows of a data frame](https://stackoverflow.com/questions/3480813/mapping-over-the-rows-of-a-data-frame) – Bulat Mar 03 '18 at 01:37
  • According to [docs](https://www.rdocumentation.org/packages/rootSolve/versions/1.7/topics/uniroot.all) most functions have an `x` variable like in algebraic functions. Where are yours as you only pass values? – Parfait Mar 03 '18 at 02:53
  • @Bulat that's what I expect answer, Than you very much ! – dawei Mar 03 '18 at 03:34

1 Answers1

1

One option is pmap from purrr after changing the column names to the input arguments in 'eqnt`

library(purrr)
library(dplyr)
library(rootSolve)
eqnt2 <- function(T, L, f){
     T^2 + T*L - f^2
 }
f2 <- function(x) pmap_dbl(df1, eqnt2)
uniroot.all(f2(), c(1,1000))
#[1]   5.653842  50.894856  51.713343  80.233553  81.052066 130.499036 131.317548 170.275345 183.660221 220.540822
#[11] 221.359340 300.145034 300.963560 337.844129 351.229033 390.186832 397.288528 440.452315 441.270803 469.791045
#[21] 470.609559 520.056547 520.875023 559.832862 573.217719 610.098309 610.916833 689.702528 690.521045 727.401642
#[31] 740.786526 779.744321 786.846019 830.009802 830.828289 859.348536 860.167027 909.614015 910.432530 949.390352
#[41] 960.697992 999.655804

Or we can use apply from base R

eqnt <- function(x) {

   x[1]^2 + x[1]*x[2] - x[3]^2   
}

library(rootSolve)
uniroot.all(apply(df1, 1, eqnt), c(1, 1000))
#[1]   5.653842  50.894856  51.713343  80.233553  81.052066 130.499036 131.317548 170.275345 183.660221 220.540822
#[11] 221.359340 300.145034 300.963560 337.844129 351.229033 390.186832 397.288528 440.452315 441.270803 469.791045
#[21] 470.609559 520.056547 520.875023 559.832862 573.217719 610.098309 610.916833 689.702528 690.521045 727.401642
#[31] 740.786526 779.744321 786.846019 830.009802 830.828289 859.348536 860.167027 909.614015 910.432530 949.390352
#[41] 960.697992 999.655804
akrun
  • 874,273
  • 37
  • 540
  • 662