【问题标题】:Replace parts of text in a list of lists in R替换R中列表列表中的部分文本
【发布时间】:2021-05-19 19:10:12
【问题描述】:

我正在尝试替换列表名称的特定部分,但我遇到了困难。在这种情况下,我只会删除有 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)

所以我试图排除 x 变量附带的数字,但我不希望删除其他变量的数字。所以我希望 mylist 是两个这样的列表的组合:

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)

我尝试使用类似下面的代码,但是其他变量的名称的数字被删除了。

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

有人可以帮助我吗?谢谢。

【问题讨论】:

    标签: r list replace names


    【解决方案1】:

    你已经快到了。只是对替换功能的一个小改动。我在下面做的是用字母 x 替换 x[然后是一些数字]。

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

    【讨论】:

    • 这非常适合我的需要。现在,我可以合并这些不同的列表非常感谢@DaveArmstrong。
    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多