1

A functionn called "myfun1" takes as an argument a single row in "my_df". The functionn calculates and returns the values for two columns (There are 12 columns) How to use lapply to call "myfun1" for all rows of my_df? The first argument to "lapply" should represents a list of "rows

joran
  • 169,992
  • 32
  • 429
  • 468
Mo Marikar
  • 33
  • 4
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Sep 24 '19 at 18:36
  • I agree that having a simple reproducible example would have been helpful. It was just that the original code was complicated with requirements for MCSIM and so on. – Mo Marikar Sep 25 '19 at 21:38

2 Answers2

0

If the function is taking numeric values as input or single class elements, then apply would be an option

 t(apply(df1, 1, myfun1))

lapply/sapply/vapply etc loop thorough the columns and not by rows. So, if we need to use lapply, then loop through the sequence of rows, and then the unit will be a single element of that sequence (with data.frame, each unit is a column)

lapply(seq_len(nrow(df1)), function(i) myfun1(df1[i,]))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Will the following solve your problem:

lapply(1:nrow(my_df),function(i){
myfun1(my_df[i,])
}
)

Let me know if that works. Thanks.