19

I'm calling apply(data, 2, function(x) {...}) where data is a matrix. Is there any way for the function to know the name of the column whose values are present in x? Or perhaps there's another function to accomplish the same task?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Suraj
  • 35,905
  • 47
  • 139
  • 250

2 Answers2

30

One common way to deal with this is to loop over the column names themselves:

m <- matrix(runif(16),4,4)
colnames(m) <- letters[1:4]
sapply(colnames(m),function(x){mean(m[,x])})
        a         b         c         d 
0.4720319 0.4992337 0.5026318 0.3514267
joran
  • 169,992
  • 32
  • 429
  • 468
18

You can use sapply on colnames(data):

set.seed(21)
Data <- matrix(rnorm(10),5,2)
colnames(Data) <- c("one","two")
sapply(colnames(Data), function(x) sum(Data[,x]))
#       one       two 
#  3.987540 -2.010875 
colSums(Data)
#       one       two 
#  3.987540 -2.010875
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418