1

How can I get all the names matching a particular value in another column (eg, all names with age 20 are Adam, Dora, Franz)?

Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
0

2 Answers 2

1

You could do the following:

\documentclass{article}
\usepackage{datatool}

\begin{filecontents}{test.csv}
Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
\end{filecontents}

\DTLloaddb{data}{test.csv}

\newcommand{\gettallnamesofage}[1]{%
    \def\allnamesofage{}%
    \DTLforeach*[\DTLiseq{\Age}{#1}]{data}{\Name=Name, \Age=Age}{%
        \ifdefempty{\allnamesofage}{%
            \let\allnamesofage\Name % first element of list
        }{% append to list
            \eappto\allnamesofage{, \Name}%
        }%
    }%
    All names with age #1 are \allnamesofage.%
}

\begin{document}

\gettallnamesofage{20}

\end{document}

Output:

enter image description here

0

This uses readarray (and listofitems) rather than datatool.

\begin{filecontents*}[overwrite]{data.dat}
Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
\end{filecontents*}
\documentclass{article}
\usepackage{readarray}
\begin{document}
\def\matchvalue{20}% VALUE TO MATCH
\def\matchcol{3}% COLUMN TO CHECK FOR \matchvalue
\def\resultcol{1}% DESIRED OUTPUT, IF MATCH
\readarraysepchar{\\}
\readdef{data.dat}\mydata
\setsepchar{\\/,}
\ignoreemptyitems
\readlist*\myarray{\mydata}
\foreachitem\z\in\myarray[]{%
  \itemtomacro\myarray[\zcnt,\matchcol]\testvalue
  \ifx\testvalue\matchvalue
    \myarray[\zcnt,\resultcol] \fi
}
\end{document}

enter image description here

1
  • Thanks, Stephen. It does work, however, I am using datatool for a bunch of other things with the same dataset and was quite keen to be able to do it with the same package
    – augusto
    Nov 12, 2021 at 15:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .