0

I have a dataframe df1 with:

file_name  loc
rep1   chr1:62161618:62162663:-
rep2   chr1:62161618:62162669:-
...

And I generate an empty matrix (df2) with file_name as rows and loc as columns. I want to add "1" value in every position that is present in df1. As an example:

     chr1:62161618:62162663:-    chr1:62161618:62162669:-...
rep1           1                            0
rep2           0                            1
...

Any suggestions? Thanks!

Tato14
  • 425
  • 1
  • 4
  • 9

1 Answers1

1

A solution using dplyr and tidyr.

library(dplyr)
library(tidyr)

dt2 <- dt %>%
  mutate(condition = 1) %>%
  spread(loc, condition, fill = 0)
dt2
#   file_name chr1:62161618:62162663:- chr1:62161618:62162669:-
# 1      rep1                        1                        0
# 2      rep2                        0                        1

DATA

dt <- read.table(text = "file_name  loc
rep1   'chr1:62161618:62162663:-'
                 rep2   'chr1:62161618:62162669:-'",
                 header = TRUE, stringsAsFactors = FALSE)
www
  • 38,575
  • 12
  • 48
  • 84
  • Hi! Thanks for the feedback! I was wondering if the code would be different if, instead of 0 and 1 I would use a third column with values in the `df1` to fill the `df2`. – Tato14 Nov 17 '17 at 20:13
  • I think you may need a join operation for that. You may want to ask a new question. – www Nov 17 '17 at 20:14