Home > Software design >  Delete table from list
Delete table from list

Time:06-29

I have list and I need to delete some table from the list. Below you can see my current solution

  imported_templates_XM$Export_FRPS5.xlsx$Sheet2<-NULL
  imported_templates_XM$Export_RP10.xlsx$Sheet2<-NULL
  imported_templates_XM$Export_RP115_AS.xlsx$Sheet2<-NULL
  imported_templates_XM$Export_RP78_AS.xlsx$Sheet2<-NULL

So any suggestion for a more elegant solution with loop ? I need to delete in each table from list Sheet 2

CodePudding user response:

I guess that what you're looking for is this:

library(purrr)
map(imported_templates_XM, assign_in, "Sheet2", NULL)

#> $Export_FRPS5.xlsx
#> $Export_FRPS5.xlsx$Sheet1
#> [1] "Keep this"
#> 
#> 
#> $Export_RP10.xlsx
#> $Export_RP10.xlsx$Sheet1
#> [1] "Keep this"
#> 
#> 
#> $Export_RP115_AS.xlsx
#> $Export_RP115_AS.xlsx$Sheet1
#> [1] "Keep this"
#> 
#> $Export_RP115_AS.xlsx$Sheet3
#> [1] "Keep this too!"
#> 
#> 
#> $Export_RP78_AS.xlsx
#> $Export_RP78_AS.xlsx$Sheet1
#> [1] "Keep this"

For each sublist, look for an object called "Sheet2" and replace its content with NULL. That automatically deletes the object.

WARNING: it "Sheet2" is not present in a sublist, you will get an error. In that case just use this:

map(imported_templates_XM, function(x){x$Sheet2 <- NULL; x})

or this:

lapply(imported_templates_XM, `[[<-`, "Sheet2", NULL)

Reproducible:

imported_templates_XM <- list(
  
  Export_FRPS5.xlsx = list(
    Sheet2 = "Delete this",
    Sheet1 = "Keep this"),
  Export_RP10.xlsx = list(
    Sheet2 = "Delete this",
    Sheet1 = "Keep this"),
  Export_RP115_AS.xlsx = list(
    Sheet2 = "Delete this",
    Sheet1 = "Keep this",
    Sheet3 = "Keep this too!"),
  Export_RP78_AS.xlsx = list(
    Sheet2 = "Delete this",
    Sheet1 = "Keep this")

)
  • Related