R number generation

On her blog, Christina Bergey has previously alluded to our discussions about number generation. I am posting my solution here, not because it is the best solution, but because it shows how R code can be written into Unix scripts (see also this previous post).

#!/bin/bash
# Arguments = vector -n digits -p prefix -s suffix

vector=$1;

digits="max(nchar($vector))";
prefix=;
suffix=;

OPTIND=2;
while getopts n:p:s: opt; do
	case $opt in
		n) digits=$OPTARG;;
		p) prefix=$OPTARG;;
		s) suffix=$OPTARG;;
	esac
done

echo "cat(paste('$prefix',formatC($vector,width=$digits,
	format='d',flag='0'),'$suffix',sep=''),sep='\\n')" | 
	/usr/bin/R --quiet --vanilla --slave

exit;

Now suppose you want to utilize the above number generation script to rename image files. Your current directory contains exactly ten .jpg images:

dog.jpg
dog_and_me.jpg
dog_at_beach.jpg
dog_in_house.jpg
dog_in_park.jpg
dog_sleeping.jpg
dog_sleeping_super_cute.jpg
dog_sleeping_super_fuzzy.jpg
dog_sneezing.jpg
dog_yawning.jpg

You can rename the files (or rather generate the Unix code for renaming them) using the paste utility and some process substitution. Example below (assumes that num is the name of the Unix script):

paste -d '\ ' <(num 'rep("mv",10)') <(ls -1 *.jpg) <(num 1:10 -p dog -s .jpg)

This outputs:

mv dog.jpg dog01.jpg
mv dog_and_me.jpg dog02.jpg
mv dog_at_beach.jpg dog03.jpg
mv dog_in_house.jpg dog04.jpg
mv dog_in_park.jpg dog05.jpg
mv dog_sleeping.jpg dog06.jpg
mv dog_sleeping_super_cute.jpg dog07.jpg
mv dog_sleeping_super_fuzzy.jpg dog08.jpg
mv dog_sneezing.jpg dog09.jpg
mv dog_yawning.jpg dog10.jpg

Running these commands in Terminal (from the proper directory) will rename all ten images. Your directory listing is now this:

dog01.jpg
dog02.jpg
dog03.jpg
dog04.jpg
dog05.jpg
dog06.jpg
dog07.jpg
dog08.jpg
dog09.jpg
dog10.jpg

As a commenter pointed out in a previous post, R can run directly from Terminal. An R session, however, runs separately from other processes and the work performed in a session cannot be passed along to other programs without the intermediate step of writing files. Here, I show how R code can be written into Unix scripts without the need to start an R session.

This entry was posted in Productivity and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *