This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Creating A New File by Combining Two Separate Files

Hello Biostar Community,

I would like to create new files by extracting values from two separate source files.

Source Files:

File A.txt

Samples C-001   C-002   C-003
Hg  R1a C2  C2
SNPs            
CTS9677     +   +
CTS103  +   +   +
P15         
F2992       +   +
CTS3607 +

where

  1. 1st Row: Sample ID
  2. 2nd Row: Y chromosome haplogroup
  3. 3rd Row: SNPs (as head for the 1st column)
  4. 4th Row and beyond: SNP ID/rsID and genotypes

File B.txt

CTS9677 Y   19020366    [A/G]
CTS7498 Y   17510288    [T/C]
CTS103  Y   2730292 [A/T]
P15 Y   23244026    [A/G]
F2992   Y   19236136    [A/G]
CTS3607 Y   15063588    [A/G]

where

  1. 1st column: SNP ID/rsID
  2. 2nd column: Chromosome
  3. 3rd column: Position of SNPs
  4. 4th column: Genotype [Ancestral/Derived]

Intended Output File:

C-001.txt

CTS9677 Y   19020366    A
CTS103  Y   2730292 T
P15 Y   23244026    A
F2992   Y   19236136    A
CTS3607 Y   15063588    G

Here, the values of the 4th column are determined by the value of 2nd column [i.e. C-001] of File A.txt [+ or blank] and the 4th column of File B.txt [Ancestral/Derived], e.g. [A/G] where A is ancestral, G is derived. In File A.txt, "blank" indicates ancestral genotype, "+" indicates derived genotype.

I would like to generate separate data files for the samples C-001, C-002, and C-003, by using an R or Python code.

Could anyone help with the issue?

snp r genome

What have you tried?

I have tried R, but not successful.

I'll rephrase: What exactly have you tried? If you shared your code and where you face a problem, people will be more willing to help you. Without evidence of effort on your part, it feels like hunting for ready-made solutions.

I can do this in Perl, but as you asked for R or Python, I can't help.

Hello h.mon,

Preferably R or Python, but Perl is also OK, as long as the problem will be solved.

Are you willing to take a walk with me?

I will not post complete code here, but I can help you write a script to perform the task you want.

By the way: horror vacui, or kenophobia. Coding ancestral genotypes as blanks is recipe for trouble.

1 answer

might need to loop twice, once to create a new column that's conditional on the 2nd column then using https://stackoverflow.com/questions/37697195/how-to-merge-two-data-frames-based-on-particular-column-in-pandas-python to create your final output file? perhaps inefficient but how many rows do you have?

Hi Kevin,

Thank you for sending the link. Actually, using R, I did the step similar to the code given in the link, but there are two difficult steps: one is to replace "+" with corresponding derived genotype and " " (blank) with corresponding ancestral genotype; and another difficult step is to run the code for all samples (over 100) by looping. There are about 2000 rows.

Log in to answer this question.