Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply over matrix by column - any way to get column name?

Tags:

r

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?

like image 406
SFun28 Avatar asked Oct 06 '11 22:10

SFun28


People also ask

How do I get the column names of a matrix in R?

The rownames and colnames functions are used to define the corresponding names of a matrix and if we want to extract those names then the same function will be used. For example, if we have a matrix called M that has row names and column names then these names can be found by using rownames(M) and colnames(M).

How do I retain a column name in R?

If x is a dataframe, use LIST SUBSETTING notation, which will keep the column name and will NOT simplify by default!

What is the function to set column names for a matrix?

colnames() function in R Language is used to set the names to columns of a matrix.

How do I sum a column with the same name?

First of all, create a data frame with some columns having same name. Then, use tapply along with colnames and sum function to find the row total of columns having same name.


2 Answers

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
like image 198
joran Avatar answered Sep 20 '22 21:09

joran


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
like image 34
Joshua Ulrich Avatar answered Sep 20 '22 21:09

Joshua Ulrich