How to quickly remove (rm
) or select (ls
) the numbered object names with a sequence in R?
In the example below, I want to delete only a1-a3.
a<-c(1:3)
a1<-c(4:6)
a2<-c(7:9)
a3<-c(10:12)
ab1c<-c(paste0("x", 1:3))
ab1c1<-c(paste0("x", 4:6))
ab1c2<-c(paste0("x", 7:9))
ab2c1<-c(1:5)
ab2c2<-c(2:6)
I know that to remove some objects quickly we use something like:
rm(list=ls(pattern="^a"))
rm(list=ls(pattern="1$"))
But, the pattern with ^
selects all variables with the initial character "a" and the pattern with $
selects all variables with "1" as the last character in their name, while I want to delete only some of them.
ls(pattern="^a")
[1] "a" "a1" "a2" "ab1c" "ab1c1" "ab1c2"
ls(pattern="1$")
[1] "a1" "ab1c1"
#what I want:
[1] "a1" "a2" "a3"
I am new to R and just knew—maybe two days ago—that my issue most possibly related to the regular expression (regex). I am starting to learn regex, but still had no luck finding how to select some objects whose name has consecutive sequence numbers. I tried to use something like pattern="1:3"
, but obviously, it does not work.
Please suggest how to select some object names with a sequence numeric pattern within them. If there is no such an expression for the numeric character in the object name, please suggest the quickest solution to remove them quickly from the global environment.
Thank you.
Edit (after the comment from Wiktor Stribiżew):
I also want to know if we can add up some criteria/argument in the pattern. For example, I want to select only "ab1c1" and "ab1c2". Could we add up some criteria like "^a", "b1", [1-2]$? I am also asking this because sometimes the number is also in the middle of the name (and sometimes I want to select by the middle character, too).
I assume you want to remove those variables that start with a
and then can have 1
, 2
or 3
, and then nothing else (i.e. end of string will follow).
Then, you may simply use ^a[1-3]$
.
If you want to find the variable names that start with a
and end with 1
, 2
or 3
, use ^a.*[1-3]$
.
See an R test:
> a<-c(1:3)
> a1<-c(4:6)
> a2<-c(7:9)
> a3<-c(10:12)
> ab1c<-c(paste0("x", 1:3))
> ab1c1<-c(paste0("x", 4:6))
> ab2c2<-c(paste0("x", 7:9))
> ls(pattern="^a")
[1] "a" "a1" "a2" "a3" "ab1c" "ab1c1" "ab2c2"
> rm(list=ls(pattern="^a[1-3]$"))
> ls(pattern="^a")
[1] "a" "ab1c" "ab1c1" "ab2c2"