Try this one.
#!/bin/bash
# Run it in the folder containing dir A and dir B.
A=A #first dir, replace with the propper name
B=B #second dir, replace with the propper name
in_file=f #replace with propper name
out_file=data.dat
B_subs=( $(ls B | sort -n) )
i=0
cd "$A"
for d in $( ls | sort -n) ; do
a="$d"/"$in_file"
b=../"$B"/"${B_subs[$i]}"/"$in_file"
((i++))
mkdir ../"$i"
# the one below is not correct, but gives your results
# join "$a" "$b" | awk '{print $1, $3-$2}' > ../"$i"/"$out_file"
# the one below is correct
join "$a" "$b" | awk '{print $1, $2-$3}' > ../"$i"/"$out_file"
done