Do Not Remove Specific Data Frame

Asked

Viewed 630 times

2

I’m working with several DF (more than 30), but I want to exclude all except one specific. Example of my DF:

DF1

VCBGF2

FGFR3

BBTYI4

QQASX5

RRTPS6

DF7

TTIPMBBT8

DF9

DF10

So I want to exclude 9 DF's, except DF 7. How do I keep only the DF7?

1 answer

5

The following function does not remove class objects obj.class corresponding to pattern.

keepObject <- function(pattern, obj.class, envir = .GlobalEnv){
  obj <- ls(envir = envir)
  obj <- obj[!grepl(pattern = pattern, obj)]
  i <- unlist(lapply(obj, function(o) inherits(get(o), obj.class)))
  rm(list = obj[i], envir = envir)
}

ls(pattern = "^DF")
# [1] "DF1"  "DF10" "DF2"  "DF3"  "DF4"  "DF5"  "DF6"  "DF7"  "DF8" 
#[10] "DF9" 

The pattern "DF7" corresponds to strings that contain "DF7". If you want you can use other regular expressions, for example "^DF7$".

keepObject("DF7", "data.frame")
ls(pattern = "^DF")
#[1] "DF7"

Dice.

DF1 <- data.frame(a = 1:10)
DF2 <- data.frame(a = 1:10)
DF3 <- data.frame(a = 1:10)
DF4 <- data.frame(a = 1:10)
DF5 <- data.frame(a = 1:10)
DF6 <- data.frame(a = 1:10)
DF7 <- data.frame(a = 1:10)
DF8 <- data.frame(a = 1:10)
DF9 <- data.frame(a = 1:10)
DF10 <- data.frame(a = 1:10)
  • 1

    Thank you. I will edit and specify my question better. Sorry.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.