代码之家  ›  专栏  ›  技术社区  ›  Wang

R中的更改列表元素

  •  1
  • Wang  · 技术社区  · 6 年前

    我有一张单子 test_list :

    a = c("name1:type", "name2:132", "445", "556")
    b = c("name1:type", "name2:132", "125", "-6")
    test_list = list(a, b)
    

    原始测试清单是:

    [[1]]
    [1] "name1:type" "name2:132"  "445"        "556"       
    
    [[2]]
    [1] "name1:type" "name2:132"  "125"        "-6" 
    

    我想换个 name1 name2 在测试列表中为“X1”、“X2”。

    我的预期产出是:

    [[1]]
    [1] "X1:type" "X2:132"  "445"        "556"       
    
    [[2]]
    [1] "X1:type" "X2:132"  "125"        "-6"   
    

    谢谢。

    3 回复  |  直到 6 年前
        1
  •  2
  •   tmfmnk    6 年前

    一种选择可能是:

    lapply(test_list, function(x) sub("name", "X", x))
    
    [[1]]
    [1] "X1:type" "X2:132"  "445"     "556"    
    
    [[2]]
    [1] "X1:type" "X2:132"  "125"     "-6" 
    

    或写为(为了避免匿名函数):

    lapply(test_list, sub, pattern = "name", replacement = "X")
    
        2
  •  1
  •   Ronak Shah    6 年前

    我们可以利用 str_replace

    purrr::map(test_list, stringr::str_replace, c('name1','name2'), c('X1', 'X2'))
    
    #[[1]]
    #[1] "X1:type" "X2:132"  "445"     "556"    
    
    #[[2]]
    #[1] "X1:type" "X2:132"  "125"     "-6"     
    
        3
  •  1
  •   jay.sf    6 年前

    你可以用 rapply .

    test_list <- rapply(test_list, gsub, pattern="name", replace="x", how="l")
    # [[1]]
    # [1] "x1:type" "x2:132"  "445"     "556"    
    # 
    # [[2]]
    # [1] "x1:type" "x2:132"  "125"     "-6"   
    
        4
  •  0
  •   akrun    6 年前

    另一种选择是 regmatches/regexpr 具有 lapply

    lapply(test_list, function(x) {regmatches(x, regexpr("name", x)) <- "X"; x})
    #[[1]]
    #[1] "X1:type" "X2:132"  "445"     "556"    
    
    #[[2]]
    #[1] "X1:type" "X2:132"  "125"     "-6"     
    
    推荐文章