Replace parts of text in a list of lists in R

Viewed 196

I'm trying to replace specific parts of list names, but I'm having a hard time. In this case, I would remove the numbers only in the parts where there is an x.

list1 <- list("L(x0801, 1)" = 1, "L(x0801, 2)" = 2, "L(x0801, 3)" =4, "rer" =2, "L(rer, 1)" = 3)
list2 <- list("L(x0901, 1)" = 1, "L(x0901, 2)" = 2, "L(x0901, 3)" =4, "L(x0901, 4)" =4, "rer" =2, "L(rer, 1)" = 3)

mylist <- list(list1, list2)

So I'm trying to exclude the numbers that come with the x variables, but I don't want the numbers of other variables to be deleted. So I wanted mylist to be a combination of two lists like these:

list1 <- list("L(x, 1)" = 1, "L(x, 2)" = 2, "L(x, 3)" =4, "rer" =2, "L(rer, 1)" = 3)
list2 <- list("L(x, 1)" = 1, "L(x, 2)" = 2, "L(x, 3)" =4, "L(x, 4)" =4, "rer" =2, "L(rer, 1)" = 3)

mylist <- list(list1, list2)

I tried to use something like the code below, but the numbers of the names of other variables are deleted.

mylist <- lapply(mylist, function(x) setNames(x, sub("\\d+", "", names(x))))

Can someone help me? Thanks.

1 Answers

You're almost there already. Just a small change to the substitution function. What I'm doing below is replacing x[and then some digits] with the letter x.

mylist <- lapply(mylist, function(x) setNames(x, sub("x\\d+", "x", names(x))))
Related