简体   繁体   中英

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, ie 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?

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"
                    x})
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))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM