How to print the name of current row when using apply in R?
r, statistics
Solution
As far as I know you cannot do that with `apply`, but you could loop through the `rownames` of your data frame. Lame example:
lapply(rownames(mtcars), function(x) sprintf('The mpg of %s is %s.', x, mtcars[x, 1]))
Problem
For example, I have a matrix `k` ``` > k d e a 1 3 b 2 4 ``` I want to apply a function on k ``` > apply(k,MARGIN=1,function(p) {p+1}) a b d 2 3 e 4 5 ``` However, I also want to print the `rowname` of the row being `apply` so that I can know which row the function is applied on at that time. It may looks like this: ``` apply(k,MARGIN=1,function(p) {print(rowname(p)); p+1}) ``` But I really don't do how to do that in R. Does anyone has any idea?