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?
Asked
Active
Viewed 2.0k times
19
Joshua Ulrich
- 173,410
- 32
- 338
- 418
Suraj
- 35,905
- 47
- 139
- 250
2 Answers
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
-
5Bah, beat me by 5 seconds! When will I learn... answer first, then edit. ;-) – Joshua Ulrich Oct 06 '11 at 22:11
-
Would `sapply(colnames(m),function(x, data){mean(data[,x])}, m)` be slightly better as it explicitly passes data into the function? – Joseph Crispell Mar 02 '21 at 15:36
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