# Tilde in lstinputlisting

I am trying to include an R file in my document. There is a tilde in one of the R commands and when I try to use \lstinputlisting{file.r}, I get the awkward tilde which appears as if it were a superscript. How can I replace this tilde with a \sim from amsmath?

Assume the content of file.r is "lm(y~x)".

\documentclass{article}

\usepackage{amsmath}
\usepackage[formats]{listings}
\lstset{ %
language=R,
basicstyle=\footnotesize\ttfamily,
}

\begin{document}
\section{Homework}
%* actual homework questions *%

\section{R Code}
\lstinputlisting{file.r}

\end{document}


Use listings' literate to replace all occurrences of ~ with $\sim$ that has a width of 2 regular characters.

\documentclass{article}

\usepackage{listings}
\lstset{
language=R,
basicstyle=\footnotesize\ttfamily,
literate=~{$\sim$}2
}

\usepackage{filecontents}
\begin{filecontents*}{file.r}
lm(y~x)
\end{filecontents*}

\begin{document}

\lstinputlisting{file.r}

\end{document}