Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace list names if they exist

I have example data as follows:

# list of data frames:
l = list(a=mtcars, b=mtcars, c=mtcars)

I would like to replace the list names, if they exist in the vector list_names_available_for_name_change with new_list_names.

list_names_available_for_name_change <- c("a", "c")
new_list_names <- c("android", "circus")

I thought of doing something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

names(l)[names(l) == "a"] <- "android"

But I would like to do this for the entire list. Something like:

names(l)[names(l) == list_names_available_for_name_change ] <- new_list_names 

How should I write the syntax to achieve this?

Desired output:

# list of data frames:
l = list(android=mtcars, b=mtcars, circus=mtcars)

>Solution :

In base R, use match to find the matching positions of the ‘names’ of the list with the subsset of list names, use that to get the corresponding ‘new_list_names’ and do the assign on the names of the list

nm1 <- new_list_names[match(names(l), list_names_available_for_name_change)]
i1 <- !is.na(nm1)
names(l)[i1] <- nm1[i1]

-output

 names(l)
[1] "android" "b"       "circus" 

Or with mapvalues

names(l) <-  plyr::mapvalues(names(l),
    list_names_available_for_name_change, new_list_names)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading