Tumi2002
Tumi2002

Reputation: 41

Awk, If test to replace 1 column with 2 columns

Good day

I have the following data matrix

1 1 0 0 1 
2 0 0 1 1 
1 1 0 0 1 
2 1 2 2 0

I would like to double the columns according to the following conditions

Condition 1   if $i == 0, replace with 1 1 (i.e. in 2 columns)
Condition 2   if  $i == 1, replace with 1 2
Condition 3    if  $i == 2, replace with 2 2

So the expected output for the example, would be

1 2  1 2  1 1 1 1 1 2 
2 2  1 1  1 1 1 2 1 2 
1 2  1 2  1 1 1 1 1 2 
2 2  1 2  2 2 2 2 1 1

I usually use R and Octave matrices but the current matrix in quiet large after a while R get out of memory and it takes long.

Upvotes: 1

Views: 526

Answers (2)

marco
marco

Reputation: 4665

If the data matrix only contains 0, 1 or 2, you could use a simple truncation trick:

awk '{
    for (i=1;i<=NF;i++) 
        printf "%d %d ", 1+ $i/2, 1+ ($i+1)/2 
}' file && echo

Upvotes: 1

Dimitre Radoulov
Dimitre Radoulov

Reputation: 27990

awk 'BEGIN {
  map[0] = "1 1"; map[1] = "1 2"; map[2] = "2 2"
  }
{
  for (i = 1; i <= NF; i++)
    printf "%s", (map[$i] (i < NF ? FS : RS))
  }' infile 

Upvotes: 2

Related Questions