创建一个"连续"矩阵运算符

时间:2017-11-17 20:26:57

标签: r

按照上一个问题: Add 0 or 1 in a df depending on conditions from another df

我现在有类似的目的,但有点不同。我有df1但有第三列"值":

file_name  loc                        num
rep1       chr1:62161618:62162663:-   3
rep2       chr1:62161618:62162669:-   5
...

我想生成一个df2矩阵,其中file_name为行,loc为列。最后,我想用df2和0填充矩阵num,其余类似于:

     chr1:62161618:62162663:-    chr1:62161618:62162669:-...
rep1           3                            0
rep2           0                            5
...

谢谢!

1 个答案:

答案 0 :(得分:3)

尝试tidyr' spread

df <- data.frame(file_name = c("rep1", "rep2"), 
           loc = c("chr1:62161618:62162663:-", "chr1:62161618:62162669:-"),
           num = c(3,5))

library(tidyr)
df <- spread(df, key = loc, value = num, fill = 0)
row.names(df) <- df$file_name
df <- df[,-1]

     chr1:62161618:62162663:- chr1:62161618:62162669:-
rep1                        3                        0
rep2                        0                        5