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
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It only takes a minute to sign up.
Sign up to join this communityYou 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:
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}