0

How do I apply a function on each elements over two Dataframes?

In the following example I want to prevent the double for-loop:

for(m in 1:nrow(DF1)) {

  for(n in 1:ncol(DF1)) {

    mySeq <- seq(DF1[m,n], DF2[m,n], 0.01)

    # Do the rest with mySeq  ... 

  }
} 

My purpose is to create sequences between each element of two dataframes with the same index.

The probably fastest solution and first thougth was mySeq <- seq(DF1, DF2, 0.01). But this doest'n work because the arguments of seq(from,to) have to be of length 1.

My second try was to use apply(). This doesn't work because it only applies on one dataframe. Then I searched for an appropriate apply solution and found mapply(). With mapply is it possible to apply on two dataframes, but there is no possibility to apply on each elements in the dataframe but rather on the rows of da dataframe. And I dont want to take use of nested apply() calls.

So my question is how to code the example shown above without using a double for-loop nor a nested apply?

Manuel
  • 2,334
  • 4
  • 20
  • 36
  • 4
    It would be easier to help if you provided a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and the desired output. – MrFlick Sep 23 '16 at 13:46
  • 3
    probably you can use `unlist` on both data.frames and then `mapply` – Cath Sep 23 '16 at 13:46
  • unlist has done the job with mapply(). Thank you ! – Manuel Sep 23 '16 at 16:12

1 Answers1

0

I'm not sure what function you are trying to apply on the elements but I have used the sweep() function for something similar in the past. For example:

df = data.frame(x = 1:10, y = 1:10, z = 1:10)
sweep(df, 1:2, 1)

Here sweep goes through every element of df and subtracts 1 but you can specify your own function to operate on the elements. Then you can either tie your 2 data frames together and use sweep() or apply it separately.

greghk
  • 91
  • 4