UPDATE: before, I used the paste
function as an example instead of an arbitrary myFun
function. That problem was slightly easier, because paste
can actually operate on vectors, while myFun
can not.
I would like to apply my own function element-wise to every element in a data.frame, and get the modified data.frame as a return value.
Example:
> df <- data.frame(c(1,2,3), c(2,3,4))
> df
c.1..2..3. c.2..3..4.
1 1 2
2 2 3
3 3 4
> df_x <- magical_apply_function(df, function(x) myFun
> df_x
c.1..2..3. c.2..3..4.
1 myFun(1) myFun(2)
2 myFun(2) myFun(3)
3 myFun(3) myFun(4)
I'm completely baffled to not be able to find the answer to this problem anywhere on the internet. Most resources talk about apply
, lapply
, and sapply
but those only work on vectors/lists and they only return lists.
Are for loops really the only way to go here?
lapply
, q.v. the @akrun answer below.