This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Convert data to 0 1 matrix in R

Hi

I have a 2 column data file .txt and I wanna convert it into a 0 1 matrix using R

Sample input

Column1 x1 x2 x3…..x100 Column2: male female both….unknown

Desired output

Column1: x1 x2 x3…..x100 Row1: male female both unknown In x1 row and male column print 1 all others 0 Same way in x2 row and female column print 1 others 0

rstudio r

1 answer

Use tidyr::pivot_longer (or reshape2::melt) and then dplyr::mutate with an ifelse. You should be able to write the exact code using these hints.

Log in to answer this question.