See the blog post "What the FPKM" by Harold Pimentel that also provides R code:
Try countToFPKM package. This package provides an easy to use function to convert the read count matrix into FPKM values normalised by library size and feature effective length. It also provides the user with a reliable function to generate FPKM heatmap plot of the highly variable features in RNA-Seq dataset.; following the equation:
fpkm() function requires three inputs to return FPKM as numeric matrix normalized by library size and feature length:
countsA numeric matrix of raw feature counts.
featureLengthA numeric vector with feature lengths that can be obtained using biomaRt.
meanFragmentLengthA numeric vector with mean fragment lengths, which can be calculate with
Picard using CollectInsertSizeMetrics.