There is no need for that function, R is pretty good at calculating averages:
mean(degree(g4))
# [1] 4.58
The number of edges is reported by ecount
:
ecount(g4)
# [1] 229
To generate a random graph that has average degree 4, you can use G(n,m) graphs. If these satisfy your needs, you can generate them using random.graph.game
:
g5 <- random.graph.game(10, 10 * 4 / 2, type="gnm")
mean(degree(g5))
# [1] 4