首页 > 解决方案 > change list elements in R

问题描述

I have a list test_list:

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

The original test_list is:

[[1]]
[1] "name1:type" "name2:132"  "445"        "556"       

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

I want to change the name1 and name2 in the test_list to "X1", "X2".

My expected output is:

[[1]]
[1] "X1:type" "X2:132"  "445"        "556"       

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

Thanks.

标签: rlist

解决方案


One option could be:

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" 

Or written as (to avoid anonymous functions):

lapply(test_list, sub, pattern = "name", replacement = "X")

推荐阅读