1

I have a data set with around 400 observations (rows). For each row I need to find the root of a function such as: f(x)= variable_1 - variable_2 + x.

For finding the root I want to use the function uniroot.all(f,interval) from the rootSolve package.

My question is, how do I do this for every row. Should I use a loop or would "apply" be more suitable to do this?

With "apply" I tried the follwing code, however I always get an error message.

> library(rootSolve)
> df<-as.data.frame(matrix(1:6,ncol=2))
> df
  V1 V2
1  1  4
2  2  5
3  3  6

> apply(df,1,uniroot.all(fun<- function(x) df$V1-df$V2 + x, interval=c(0,100)))

Thanks a lot!

Dason
  • 60,663
  • 9
  • 131
  • 148
Heike
  • 13
  • 3
  • Is this literally your problem or are you just providing a simplified example? Otherwise x = -(df$V1 - df$V2) is your solution and there is no need to use uniroot. – Dason Aug 19 '12 at 18:22
  • It's just a simplified example. – Heike Aug 19 '12 at 18:41

1 Answers1

1

Here is the correct syntax when using apply:

apply(df, 1,
      function(z) uniroot.all(function(x)z[1]-z[2]+x,
                              interval = c(0,100)))
# [1] 3 3 3

Personally, I like using the plyr package for this kind of things, so I can access variables by their column names (here V1 and V2):

library(plyr)
adply(df, 1, summarize,
      solution = uniroot.all(function(x)V1-V2+x,
                             interval = c(0,100)))
#   V1 V2 solution
# 1  1  4        3
# 2  2  5        3
# 3  3  6        3
flodel
  • 87,577
  • 21
  • 185
  • 223