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?
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).
If x is a dataframe, use LIST SUBSETTING notation, which will keep the column name and will NOT simplify by default!
colnames() function in R Language is used to set the names to columns of a matrix.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With