Create a list of data matching the pattern

This is a very simple question, however I cannot find the answer. I would like to create a list data frames

that matches the pattern and then rm

from the global environment.

The matching pattern is ' water_land_by_owntype_*

'

This is what I tried but it doesn't work ... I think b / c it doesn't know where to look for the string.

rm (matches <- list(
    grep('water_land_by_owntype_*')))

      

-al

+3


source to share


2 answers


Hi, you can do the following:



# Create some data.frame
water_land_by_owntype_1 <- mtcars
water_land_by_owntype_2 <- mtcars
water_land_by_owntype_3 <- mtcars
water_land_by_owntype_4 <- mtcars
water_land_by_owntype_5 <- mtcars

# Put them in a list
water_land_by_owntype <- lapply(ls(pattern = "water_land_by_owntype_.*"), get)

# or more directly
water_land_by_owntype <- mget(ls(pattern = "water_land_by_owntype_.*"))

# Delete them
rm(list = ls(pattern = "water_land_by_owntype_.*"))

      

+4


source


This might be the easiest way to do it. 1. Retrieve variables via ls ()
2. Detect (return boolean) pattern
3. Find and subset
4. Remove

library(stringr)
a = ls()
index = which(str_detect(ls, "water_land_by_owntype_"))
b = a[index]
rm(b)

      



Hope it helps,

0


source







All Articles