3

I am trying to do a web search that will return several data frames (of different sizes), based on zip codes. I would like to dump each search result into a data frame named after the zip code.

require(XML)
zip <- c(zip1, zip2, zip3, etc)
k <-4        #index for the table that needs to be retrieved

for (i in 1:length(zip)) {
url <- paste(text1, zip[i], text2, sep="")
resultsdataframe <- data.frame (readHTMLTable(url), which = k)
}

So my question is: how can I get different names for resultsdataframe, each named dynamically from zip[i]? Many thanks.

  • 1
    http://stackoverflow.com/questions/6034655/r-how-to-convert-string-to-variable-name , http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f – Ben Bolker Feb 03 '13 at 20:46

1 Answers1

2

You can use sapply , it will assign names for you.

sapply(zip, function(x)
{
  url <- paste(text1, x, text2, sep="")
  data.frame (readHTMLTable(url), which = k)
}

For example

zip <- paste('zip',1:5, sep ='')
ll <- sapply(zip, function(x)
   {
     data.frame ()
   })

ll
$zip1
data frame with 0 columns and 0 rows

$zip2
data frame with 0 columns and 0 rows
.... 

No need to use assign. You can access your list like this

ll[['zip1']]
data frame with 0 columns and 0 rows
agstudy
  • 119,832
  • 17
  • 199
  • 261