Here's a neat solution to what I think you're asking. (I've called the input matrix mat
rather than k
for clarity - in this example, mat
has 2 columns and 10 rows, and the rows are named abc1 through to abc10.)
In the code below, the result out1
is the thing you wanted to calculate (the outcome of the apply command). The result out2
comes out identically to out1
except that it prints out the rownames that it is working on (I put in a delay of 0.3 seconds per row so you can see it really does do this - take this out when you want the code to run full speed obviously!)
The trick I came up with was to cbind the row numbers (1 to n) onto the left of mat
(to create a matrix with one additional column), and then use this to refer back to the rownames of mat
. Note the line x = y[-1]
which means that the actual calculation within the function (here, adding 1) ignores the first column of row numbers, which means it's the same as the calculation done for out1
. Whatever sort of calculation you want to perform on the rows can be done this way - just pretend that y
never existed, and formulate your desired calculation using x
. Hope this helps.
set.seed(1234)
mat = as.matrix(data.frame(x = rpois(10,4), y = rpois(10,4)))
rownames(mat) = paste("abc", 1:nrow(mat), sep="")
out1 = apply(mat,1,function(x) {x+1})
out2 = apply(cbind(seq_len(nrow(mat)),mat),1,
function(y) {
x = y[-1]
cat("Doing row:",rownames(mat)[y[1]],"
")
Sys.sleep(0.3)
x+1
}
)
identical(out1,out2)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…