How to convert a dataframe to a matrix in R -
i want transfer named vector matrix , fill missing values (fill 0s).
for example, have dataframe this:
col1 col2 col3 cancer1 gene1 2.1 cancer1 gene2 2.51 cancer1 gene3 3.0 cancer2 gene1 0.9
which has 2 columns of names: col1
, col2
. want transform matrix, like:
cancer1 cancer2 gene1 2.1 0.9 gene2 2.51 0 gene3 3.0 0
if there missing values in vector, fill 0s.
how can efficiently in r?
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))
Comments
Post a Comment