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:
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)
CodePudding user response:
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)