-1

I have a data frame d and a function f that takes each row of the data frame to return a data frame:

d <- data.frame(x=c(1,2,3),y=c(11,22,33))

f <- function(row){
...
return(df)
}

Now, I want to apply f to d (to avoid looping through f(d[k,] of course). apply can´t work and putting the rows of d in a list and using lapply failed. What should I do?

Claudio Moneo
  • 489
  • 1
  • 4
  • 10
  • Does this answer your question? [R: apply-like function that returns a data frame?](https://stackoverflow.com/questions/36982755/r-apply-like-function-that-returns-a-data-frame) – caldwellst Aug 12 '20 at 09:53
  • `apply(d, 1, f)` doesn't work? How about `lapply(asplit(d, 1), f)` ? – Ronak Shah Aug 12 '20 at 10:02
  • @RonakShah No, I get "$ operator is invalid for atomic vectors" despite `f` working fine for all rows (`d[k,]`) seperately – Claudio Moneo Aug 12 '20 at 10:07

1 Answers1

1

You haven't shown what you have in f but based on comments it is written for dataframes, so this should work :

lapply(split(d, seq_len(nrow(d))), f)

split divides every row of d in 1 row-dataframe and using lapply we apply function f on each row.

You can also use by :

by(d, seq_len(nrow(d)), f)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213