[R] Renaming multiple objects

Steven Yen @tyen @end|ng |rom ntu@edu@tw
Mon Nov 22 03:58:38 CET 2021


Thanks to all who responded and helped. It worked great!

On 2021/11/20 下午 10:31, Rui Barradas wrote:
> Hello,
>
> You can get all objects to be changed into a list, change the list's 
> names attribute and assign back to the globalenv. Something like the 
> following.
> First see if the objects exist in the global env.
>
> ls()
> #[1] "meb1.p.emb"  "meb2.p.emb"  "mec1.p.emb"  "mec2.p.emb"
> #[5] "mej12.p.emb" "mej22.p.emb"
>
>
> Now the code to change their names
>
>
>
> # create a vector of names of the objects
> # whose names are to be changed
> obj_names <- ls(pattern = "\\.emb$")
>
> # this is instruction is not strictly needed
> # it's meant to check if the regex works (it does)
> sub("\\.emb$", "", obj_names)
> #[1] "meb1.p"  "meb2.p"  "mec1.p"  "mec2.p"  "mej12.p" "mej22.p"
>
> # get the objects into a list
> tmp_list <- mget(obj_names, envir = .GlobalEnv)
> # change the list's names
> names(tmp_list) <- sub("\\.emb$", "", obj_names)
> # assign them to the global environment
> list2env(tmp_list, envir = .GlobalEnv)
>
> # clean up
> rm(tmp_list)
> rm(list = obj_names)
>
> # check to see if it worked (it did)
> ls()
> #[1] "meb1.p"  "meb2.p"  "mec1.p"  "mec2.p"  "mej12.p" "mej22.p"
>
>
> Hope this helps,
>
> Rui Barradas
>
> Às 10:27 de 20/11/21, Steven Yen escreveu:
>> I have named NUMEROUS objects (each containing, e.g., 48 obs. of 5 
>> variables), such as
>>    mec1.p.emb
>>    mec2.p.emb
>>    meb1.p.emb
>>    meb2.p.emb
>>    mej12.p.emb
>>    mej22.p.emb
>>
>> How would I rename these objects removing the silly ".emb", into objects
>>    mec1.p
>>    mec2.p
>>    meb1.p
>>    meb2.p
>>    mej12.p
>>    mej22.p
>>
>> Thank you!
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list