Insert word count into sweave/knitr documents

useful trick found on stackexchange

1. install texcount and enable write18.

2. add this to your preamble:

\newcommand\wordcount{
\immediate\write18{texcount -sub=section \jobname.tex | grep "Section" | sed -e 's/+.*//' | sed -n \thesection p > 'count.txt'}
(\input{count.txt}words)}

3. Insert the following into your rnw file, changing myfile to the name of your rnw file:
\makeatletter\@@input|"echo `texcount -1 myfile.tex`| cut -c1-4"\makeatother