Maybe something like this?
library(XML)
tg<-xmlToDataFrame("http://www.xmldatasets.net/temp/179681356453762.xml")
mt<-data.frame(fname=cbind(apply(tg[,2:3],1,function(x) paste0(x,collapse=", "))),state=tg$state)
mt[mt$state=="TX",]
fname state
28 Cornyn, John TX
43 Hutchison, Kay Bailey TX
As commented below, if you do not want to collapse the family name and first name to one column you could just take the converted XML table, tg
, and type:
tg[tg$state=="TX",]
To get all the info about the senators in Texas. And if you need only the name and the state you could subset it as:
tg[tg$state=="TX",c(2:3,5)]
If you want to be able to type the state name in the console and get the name and states:
for (j in unique(tg$state)){
assign(j,tg[tg$state==j,c(2,3,5)])
}
And then type the state name, e.g. MT
, and get the output:
> MT
last_name first_name state
5 Baucus Max MT
89 Tester Jon MT
And you can also make a function of this:
senatorName<-function (x) tg[which(tg$state==paste0(x)),c(2:3,5)];
> senatorName("TX")
last_name first_name state
28 Cornyn John TX
43 Hutchison Kay Bailey TX