1

I currently have a while loop to read HTML tables and in each loop I would like to change the column names to the first row of the current data frame. Let's say I have a data frame named "df1". I could accomplish this with the following code:

colnames(df1) = unlist(df1[1,])

And that works fine, but I can't specify df1 in the loop because it could be df1, df2, and so on depending on what i equals.

I wrote the following code:

colnames(eval(parse(text=paste0("df",1)))) = unlist(eval(parse(text=paste0("df",1)))[1,])

I replaced i with 1 for testing purposes, but I get the following error:target of assignment expands to non-language object

If I run colnames(eval(parse(text=paste0("df",1)))) on its own, the data looks the same as colnames(df1) and same with unlist(eval(parse(text=paste0("df",1)))[1,]) looking like unlist(df1[1,]).

Any help on this will be much appreciated!

d84_n1nj4
  • 1,569
  • 6
  • 21
  • 36
  • See gregor's answer to this [related post](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) on working with lists of data.frames. You should follow this advice and read these data.frames into a list. It will make working with them easier. – lmo Aug 25 '16 at 14:42
  • Hi @lmo, I put these data frames into a list after the while loop completes. Should I work with the column names outside of the while loop in this case? If it's easier, I'll just do that--I didn't know if there was a quick fix to my issue or not. – d84_n1nj4 Aug 25 '16 at 15:02
  • If the renaming process is uniform across data.frames, then putting them all into a list and performing the renaming in an `lapply` or the like would make more sense then the `eval` / `parse` paradigm. – lmo Aug 25 '16 at 15:14
  • Ok @lmo, I put my data frames into a list using `df_lst – d84_n1nj4 Aug 25 '16 at 16:25
  • I just updated my for loop to this: `i – d84_n1nj4 Aug 25 '16 at 16:33
  • 1
    Your `for` loop is only acting on item 1. Use `for(i in seq_along(df_lst))` instead. Also, I'd recommend building lists from data.frames using `df_lst – lmo Aug 25 '16 at 17:11
  • Thanks for your help with this @lmo!! I'm still learning a lot about R, and you've been very insightful. I'll start to use your method of building lists from data.frames. I would close this question but I don't have the ability to do so yet. – d84_n1nj4 Aug 25 '16 at 17:26

0 Answers0