Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically assign names to dataframes?

Tags:

r

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.

like image 980
K Owen - Reinstate Monica Avatar asked Jun 03 '26 04:06

K Owen - Reinstate Monica


1 Answers

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
like image 132
agstudy Avatar answered Jun 05 '26 21:06

agstudy