按照上一个问题: 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
...
谢谢!
答案 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