Tuesday, May 14, 2024
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 495  / 2 Years ago, tue, april 5, 2022, 5:45:43

I have a file, say 'test.txt' with:



5 80  
3 70
4 60


Now I want to create an R plot that looks like stairs/steps: y-value 80 for 5 data points, then y-value 70 for 3 data points and then y-value 60 for 4 data points, something like this:



stairs plot example



How could I transform the test.txt to transformed.txt:



80  
80
80
80
80
70
70
70
60
60
60
60


on the shell, or, alternatively directly print the plot in R from test.txt.


More From » command-line

 Answers
0

AWK is good for this:



awk '{while ($1-- > 0) print $2}' test.txt


This interprets each line of test.txt as a record of fields separated by spaces. It counts down (--) from the value of the first field ($1) until that value is zero, printing the value of the second field ($2) on its own line each time.



One of the advantages of this method is that it automatically tolerates extra whitespace before, in between, or after the numbers.



Specifically:





If you prefer, you can instead use a for-loop:



awk '{for (; $1 > 0; --$1) print $2}' test.txt


Or with a dedicated loop counter variable:



awk '{for (i = $1; i > 0; --i) print $2}' test.txt


Or if you find it more intuitive to count up instead of down, you can do that:



awk '{for (i = 0; i < $1; ++i) print $2}' test.txt

[#12484] Tuesday, April 5, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
azaaburge

Total Points: 266
Total Questions: 85
Total Answers: 109

Location: Djibouti
Member since Sat, Oct 29, 2022
2 Years ago
;