The following macro \isincluded uses the same test that \include uses
(code copied from there). If the file in the first argument will be included,
then the second argument is called, otherwise the third. Also the macro catches
the case, when \includeonly is not used and all files are included.
\documentclass{article}
\includeonly{file,file2}
\makeatletter
\newcommand*{\isincluded}[1]{%
\@tempswatrue
\if@partsw
\@tempswafalse
\edef\reserved@b{#1}%
\@for\reserved@a:=\@partlist\do
{\ifx\reserved@a\reserved@b\@tempswatrue\fi}%
\fi
\if@tempswa
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\makeatother
\isincluded{file1}{%
\usepackage{apackage}%
}{}
\begin{document}
\include{file1}
\include{file2}
\end{document}
If \includeonly is used the switch \if@partsw is true. Then the files of \includeonly are available in \@partlist.
Extension: \isincluded with list of files
Use case: Resources (packages) must be loaded if some files are included. That means if either of the files in \isincluded will be included, then the test of
\isincluded evaluates to true (comma is "or" operator):
\documentclass{article}
\includeonly{file1,file3}
\makeatletter
\newcommand*{\isincluded}[1]{%
\@tempswatrue
\if@partsw
\@tempswafalse
\edef\isincluded@list{\zap@space#1 \@empty}% removes spaces in file list
\@for\reserved@b:=\isincluded@list\do{%
\@for\reserved@a:=\@partlist\do{%
\ifx\reserved@a\reserved@b\@tempswatrue\fi
}%
}%
\fi
\if@tempswa
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\makeatother
\isincluded{file2,file3}{%
\usepackage{apackage}%
}{}
\begin{document}
\include{file1}
\include{file2}
\include{file3}
\end{document}