0

Following this previous question: Add 0 or 1 in a df depending on conditions from another df

I have now a similar purpose but a bit different. I have df1 but with a third column "value":

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

I would like to generate a df2 matrix with file_name as rows and loc as columns. Finally I want to fill the matrix df2 with the values from num and 0 for the rest, something like:

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

Thanks!

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
Tato14
  • 425
  • 1
  • 4
  • 9

1 Answers1

3

Try tidyr's 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
Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98