0

So I'm trying to find the roots for specific values of Y with uniroot(). I have them all in a column in a dataframe, and I want to create a new column with the root found for each one of the Ys of the original column via lapply(). The way I'm creating the function that uniroot takes as an argument to find its roots, is I am substracting the Y value to the last coefficient of this function, and that Y value is passed as an extra argument to uniroot (according to the uniroot help page).

After a couple hours trying to figure out what was happening I realized that the value that lapply() feeds to the function is the Y, but it's being read as the argument "interval" inside uniroot, thus giving me errors about this argument.

I think I could implement this another way, but it'd be much better and simpler if this way has a solution.

pol_mod <- lm(abs_p ~ poly(patron, 5, raw = TRUE), data = bradford)

a <- as.numeric(coefficients(pol_mod)[6])
b <- as.numeric(coefficients(pol_mod)[5])
c <- as.numeric(coefficients(pol_mod)[4])
d <- as.numeric(coefficients(pol_mod)[3])
e <- as.numeric(coefficients(pol_mod)[2])
f <- as.numeric(coefficients(pol_mod)[1])

fs <- function (x,y) {a*x^5 + b*x^4 + c*x^3 + d*x^2 + e*x + f - y}

interpol <- function (y, fs) {
    return(uniroot(fs,y=y, interval=c(0,2000)))
}

bradford$concentracion <- lapply(bradford$abs_m, interpol, fs=fs)

The error I'm getting:

Error in uniroot(fs, y = y, interval = c(0, 2000)) : 
  f.lower = f(lower) is NA

Needless to say, everything works when applied outside of lapply()

I'd be really happy If someone could lend a hand! Thanks in advance!

EDIT: This is how the dataframe looks like.

bradford
# A tibble: 9 x 3
  patron abs_p  abs_m
   <dbl> <dbl>  <dbl>
1      0 0      1.57 
2     25 0.041  1.27 
3    125 0.215  1.59 
4    250 0.405  1.61 
5    500 0.675  0.447
6    750 0.97   0.441
7   1000 1.23  NA    
8   1500 1.71  NA    
9   2000 2.04  NA
jpm92
  • 143
  • 1
  • 8
  • 1
    if abs_m is NA, it gives you that error right (see row 7 to 9)? – StupidWolf Nov 21 '19 at 13:33
  • Wow, it indeeds solves the problem if I fill that rows...but the result I get is wrong anyway, I get "" in every row of the new column... :/ Is there any way to tell the function to omit the NAs? (when I do na.rm=TRUE I get an error saying that the argument is unused) – jpm92 Nov 21 '19 at 15:34
  • 1
    try this; bradford$concentracion <- NA; bradford$concentracion[!is.na(bradford$abs_m)] <- lapply(bradford$abs_m[!is.na(bradford$abs_m)], interpol, fs=fs) – StupidWolf Nov 21 '19 at 16:35
  • you fill the column with NA, and you substitute the non NA entries – StupidWolf Nov 21 '19 at 16:36
  • That works! Thanks a lot! I'm finding R very annoying with NAs...couldn't I just tell him to just ignore them? Even when you try to append a column that has a different length than the others to a dataframe everything is a problem...Thanks anyway! :) – jpm92 Nov 21 '19 at 19:42

0 Answers0