I have a data frame with dimensions 3695 X 20. The first column contains alphanumeric identifiers, the other 19 columns are all numeric. So, rownames(df) provides the numbers 1-3695, and colnames(df) gives the names of the columns. df[,1] provides the alphanumeric identifiers.
I would like to convert the data frame to a matrix and use column 1 of the existing data frame to be the rownames of the new matrix and maintain the column names of the data frame as the column names of the matrix.
I would also like to automate this process for use with data frames of similar but different dimensions. So, if the solution to this requires knowing the number of rows and/or columns, how can I get this information into the code without me having to look at the monitor ?
I have looked at data.matrix and reshape2 but can not seem to figure out how to do what I want.
With your sample data
X<-structure(list(gene = c("AT1G01040", "AT1G01270", "AT1G01471", "AT1G01680"), log2.fold_change._Mer7_2.1_Mer7_2.2 = c(0, 0, 0, 0), log2.fold_change._Mer7_1.2_W29_S226A_1 = c(0, 0, -1.14, 0 ), log2.fold_change._Mer7_1.2_W29_1 = c(0, 0, 0, 0)), .Names = c("gene", "log2.fold_change._Mer7_2.1_Mer7_2.2", "log2.fold_change._Mer7_1.2_W29_S226A_1", "log2.fold_change._Mer7_1.2_W29_1"), row.names = c(NA, 4L), class = "data.frame")
You can write a simple helper function to create a matrix and set the right names
matrix.please<-function(x) {
m<-as.matrix(x[,-1])
rownames(m)<-x[,1]
m
}
and you would use it like
M <- matrix.please(X)
str(M)
# num [1:4, 1:3] 0 0 0 0 0 0 -1.14 0 0 0 ...
# - attr(*, "dimnames")=List of 2
# ..$ : chr [1:4] "AT1G01040" "AT1G01270" "AT1G01471" "AT1G01680"
# ..$ : chr [1:3] "log2.fold_change._Mer7_2.1_Mer7_2.2"
# "log2.fold_change._Mer7_1.2_W29_S226A_1" "log2.fold_change._Mer7_1.2_W29_1"
So we have a 4x3 matrix with the correct row and col names.
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