0

I have multiple dataframes (example below) in my global environment and want to search through all of them for keywords.

df1<-data.frame(col1=c("laptop","fridge","basket"))
df2<-data.frame(col1=c("TV","Radio","Car"))
df3<-data.frame(column1=c("TV","Candle","laptop"))

In this example, is there a way to query all the dataframes and return a list of dataframes where TV is listed?

Basil
  • 361
  • 1
  • 14
  • One could always use `ls()` to find object names, check with `is.data.frame`, then `sapply(get(.), ...)`. Is there a reason you have them as separate frames instead of a list of multiple frames? (https://stackoverflow.com/a/24376207/3358227) – r2evans Feb 01 '21 at 22:26

3 Answers3

0

Perhaps you can try the code below

subset(
  lst <- mget(ls(pattern = "df\\d")),
  sapply(lst, function(v) any(v == "TV")),
)

which gives

$df2
   col1
1    TV
2 Radio
3   Car

$df3
  column1
1      TV
2  Candle
3  laptop
ThomasIsCoding
  • 53,240
  • 4
  • 13
  • 45
0

How about something like this? It finds all of the elements in your workspace and returns TRUE or FALSE for the data frames and NA for things that aren't data frames.

df1<-data.frame(col1=c("laptop","fridge","basket"))
df2<-data.frame(col1=c("TV","Radio","Car"))
df3<-data.frame(column1=c("TV","Candle","laptop"))
df4 <- 3

elems <- ls()
sapply(elems, function(x){
  tmp <- eval(parse(text = x))
  if(inherits(tmp, "data.frame")){
    length(sapply(1:ncol(tmp), function(i)grep("TV", tmp[[i]]))[[1]]) > 0
  }else{
    NA
  }
})

#   df1   df2   df3   df4 
# FALSE  TRUE  TRUE    NA
DaveArmstrong
  • 6,161
  • 1
  • 5
  • 14
0

You can also use Filter :

Filter(function(x) any(x == 'TV'), mget(ls(pattern = 'df\\d+')))

#$df2
#   col1
#1    TV
#2 Radio
#3   Car

#$df3
#  column1
#1      TV
#2  Candle
#3  laptop

To get the names of dataframes :

names(Filter(function(x) any(x == 'TV'), mget(ls(pattern = 'df\\d+'))))
#[1] "df2" "df3"
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143