简体   繁体   中英

Apply function on each element in two Dataframes using R

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?

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM