0

I have a embedded lists as follows.

which I get after running this code

dfs <- lapply(mf_sheets, data.frame, stringsAsFactors = FALSE)

dfs

$`DSP BlackRock Equity Fund`
Sr_No         Scrip_Name         Industry 
1               ABC                AUTO
2               DEF                IT
3               WER                Software

$DSP_BlackRockTop100_Equity_Fund

Sr_No         Scrip_Name         Industry 
1               ABC                AUTO
2               DEF                IT
3               WER                Software

I have 17 embedded lists in one lists like above . What I want to do is save all this as seperate dtaframe with list name as dataframe name.

How would I do it in R?

Neil
  • 7,937
  • 22
  • 87
  • 145

1 Answers1

1
sheet1 <- list(ID = 1:5, value = LETTERS[1:10])
sheet2 <- list(ID = 1:5, value = letters[1:10])
all.sheets <- list(sheet.1 = sheet1, sheet.2 = sheet2)

# Edit: Do guarantee unique and syntactically correct variable names via "make.names"
valid.names <- make.names(names(all.sheets), unique = TRUE)

for(i in seq_along(all.sheets)) {
  assign(valid.names[i], as.data.frame(all.sheets[i]))
}

Edit 2: Warning: This solution answers the question of the OP but has severe side-effects, e. g. overwriting any existing variables with the same name in the current environment. As mentioned by multiple users here it would be better to keep the list elements in a "container" (e. g. a list or environment) to avoid side-effects and improve the programming style (e. g. generic processing via "loops" over the container)...

For details see: https://stackoverflow.com/a/17559641/4468078

R Yoda
  • 8,358
  • 2
  • 50
  • 87
  • OP has list of dataframes, not list of lists. – zx8754 May 25 '17 at 07:31
  • @zx8754 I am not sure about that: The OP mentioned: "I have 17 embedded lists in one lists like above". Without a MRE it stays unclear... – R Yoda May 25 '17 at 07:32
  • 2
    Then they might have 17 lists with many dataframes in each. Anyway OP needs to clarify. – zx8754 May 25 '17 at 07:35
  • `library("fortunes"); fortune(236)` https://stackoverflow.com/questions/17559390/why-is-using-assign-bad – jogo May 25 '17 at 07:50
  • @jogo I should add `fortunes` to my `.rprofile` ;-) Could you please explain why exactly `assign` is dangerous here and how a better solution could look like to provide a better guidance? – R Yoda May 25 '17 at 08:05
  • Can we also add name of the list as one of the dataframe column. which will contain repeated name till the end of dataframe rows. – Neil May 25 '17 at 10:34