This is a test version of Biostars. For the public version, visit https://www.biostars.org.
short genotype format

Hello,

Using Linux (or may be R), what is the most efficient way to transform long genotype format into short format?

Input file:

11130012
33221200

Transformation: 11 into 0; 12 or 13 into 1; 22 or 33 into 2 and 00 into 5.

The output file would be:

0151
2215
snp

2 answers

efficient ?

using Flex + gcc:

file: biostar.l

%option noyywrap
%%
11 putchar('0');
(12|13) putchar('1');
(22|33) putchar('2');
00 putchar('5');
\n ECHO;
. fprintf(stderr,"ERROR!");exit(-1);
%%
int main(int argc,char argv) { yylex();return 0;}

usage:

flex biostar.l  && gcc -O3 lex.yy.c && echo -e '11130012\n33221200' | ./a.out 
0151
2215

Thanks Pierre. Efficient because the file is too big. I got this error -bash: fg: %option: no such job

??? there is something wrong in you command. what is fg ?

what is the output of flex --version. should be something like:

$ flex --version
flex 2.6.0

fg is is for background jobs. it's unrelated to the present question.

Python

d = {"11": "0",  "12" : "1", "13" : "1", "22" : "2", "33" : "2", "00" : "5"}

def long_to_short(input):
    string = ""
    output = ""
    for i in input:
        string += i
        if len(string) == 2:
            output += d[string]
            string = ""
    print(output)

It works well! Could you please modefy the code so it reads inputs from a file and sends outputs to a file?

This should work if you just replace the "input.txt" with the filename to your input file

import os
cwd = os.getcwd()
d = {"11": "0",  "12" : "1", "13" : "1", "22" : "2", "33" : "2", "00" : "5"}

def long_to_short(input):
    string = ""
    output = ""
    for i in input:
        string += i
        if len(string) == 2:
            output += d[string]
            string = ""
    return(output)
f = open(input.txt, "r")
o = open(cwd + "/output.txt", "w")
for i in f.readlines():
    o.write(long_to_short(i.replace("\n", "")) + "\n")

Thanks shussainather! Yup! It works just fine and does exactly what I want. One thing: name of input file should be between " " i.e. "input.txt"

Log in to answer this question.