apply - Looping through an id using lapply() in R -
i have written function this:
myfunc <- function(data, c1, c2, c3) { res <- data*c1*c2*c3 return(res) }
to apply myfunc
on vector data
use
lapply(data, myfunc, c1=2, c2=3, c3=4)
but have loop through id along vector data
, every row of resulting vector (or matrix) contains id , respective result.
so simple case be:
myfunc <- function(id, data, c1, c2, c3) { res <- data*c1*c2*c3 return(c(id, res)) }
but cant utilize lapply
on that. tried set input (id, data, c1, c2, c3
) in matrix utilize apply
:
apply(matrix, 1, myfunc)
but did not work.
so best way accomplish this?
thanks in advance!
edit:
this info matrix:
id info c1 c2 c3 [1,] 32 1.12 2 2.5 2.8 [2,] 33 1.14 2 2.5 2.8 [3,] 34 1.21 2 2.5 2.8 [4,] 35 1.22 2 2.5 2.8 [5,] 36 1.27 2 2.5 2.8 [6,] 37 1.30 2 2.5 2.8 [7,] 38 1.32 2 2.5 2.8 [8,] 39 1.36 2 2.5 2.8 [9,] 40 1.44 2 2.5 2.8 [10,] 41 1.45 2 2.5 2.8
column id shall looped through , myfunc shall applied on other columns. expect (or demand) result this:
id res [1,] 32 15.68 [2,] 33 15.96 [3,] 34 16.94 [4,] 35 17.08 [5,] 36 17.78 [6,] 37 18.20 [7,] 38 18.48 [8,] 39 19.04 [9,] 40 20.16 [10,] 41 20.30
why not have info in dataframe , then:
> ddf$res = with(ddf, data*c1*c2*c3) > ddf id info c1 c2 c3 res [1,] 32 1.12 2 2.5 2.8 15.68 [2,] 33 1.14 2 2.5 2.8 15.96 [3,] 34 1.21 2 2.5 2.8 16.94 [4,] 35 1.22 2 2.5 2.8 17.08 [5,] 36 1.27 2 2.5 2.8 17.78 [6,] 37 1.30 2 2.5 2.8 18.20 [7,] 38 1.32 2 2.5 2.8 18.48 [8,] 39 1.36 2 2.5 2.8 19.04 [9,] 40 1.44 2 2.5 2.8 20.16 [10,] 41 1.45 2 2.5 2.8 20.30
r apply lapply
No comments:
Post a Comment