First u can use (show_group) param in your {categories} loop instead off {if} condition
{categories show_group="4"}
......
{/categories}
{categories show_group="1"}
......
{/categories}
and if you want to use {if} condition then change your code to :
{categories}
{if {category_group_id} == 4} {!-- formats --}
......
{/if}
{/categories}
{categories}
{if {category_group_id} == 1} {!-- formats --}
......
{/if}
{/categories}
the trick here is to around category_group_id variable with parentheses.
Note: this hack is in EE2.8.0 in another version maybe the line number will be different.
Regard's.