Tian Tian -3 years ago 160
R Question

How to convert a dataframe to a matrix in R

I want to transfer a named vector to matrix and fill up missing values (fill with 0s).

For example, I have a dataframe like this:

col1 col2 col3
Cancer1 Gene1 2.1
Cancer1 Gene2 2.51
Cancer1 Gene3 3.0
Cancer2 Gene1 0.9


Which has two columns of names:
col1
and
col2
. Then I want to transform this into a matrix, like:

Cancer1 Cancer2
Gene1 2.1 0.9
Gene2 2.51 0
Gene3 3.0 0


If there are missing values in the vector, fill with 0s.

How can I do this efficiently in R?

Answer Source

You can use tidyr package:

tidyr::spread(mydata, col1, col3, fill = 0)

#    col2 Cancer1 Cancer2 
# 1 Gene1    2.10     0.9 
# 2 Gene2    2.51     0.0 
# 3 Gene3    3.00     0.0

Data:

mydata <- structure(list(col1 = structure(c(1L, 1L, 1L, 2L), .Label = c("Cancer1", 
"Cancer2"), class = "factor"), col2 = structure(c(1L, 2L, 3L, 
1L), .Label = c("Gene1", "Gene2", "Gene3"), class = "factor"), 
col3 = c(2.1, 2.51, 3, 0.9)), .Names = c("col1", "col2", 
"col3"), class = "data.frame", row.names = c(NA, -4L))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download