dimebucker91 dimebucker91 - 1 year ago 73
R Question

changing specific names in list of lists in R

I've got a list of lists in R. I've created the following example list to illustrate my problem:

example_list <- list(
list(id1 = 123, id2 = 321, school = 'notting'),
list(id3 = 12, house = 'Y'),
list(id4 = 18)

What I want to do is basically replace the name of the id elements to one consistent name, i.e. id. so my output would be:

solution_list <- list(
list(id = 123, id = 321, school = 'notting'),
list(id = 12, house = 'Y'),
list(id = 18)

Note that a sub list may contain multiple id_ elements.

I've written this function to act on each sublist:

replace_names<- function(x, r) {
indices <- grepl(r, names(x))
if(length(indices) > 0) {names(x)[indices] <- r}


my idea was to use:

lapply(example, replace_names, r = "id")

though my function isn't working for some reason, and the approach seems a bit hacky, any suggestions?

Answer Source

We replace the names of the list elements that have 'id' followed by numbers (using grep) to 'id', and return the list element.

sol_list <- lapply(example_list, function(x) {
                   names(x)[grep("id", names(x))] <- "id"
identical(solution_list, sol_list)
#[1] TRUE

Or another option is using sub to remove the numbers from the names (as there is only 'id' with numbers as suffix

lapply(example_list, function(x) setNames(x, sub("\\d+", "", names(x))))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download