Wang
Wang

Reputation: 1460

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.

Upvotes: 1

Views: 60

Answers (4)

akrun
akrun

Reputation: 887891

Another option is to use regmatches/regexpr with 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"     

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 40171

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

Upvotes: 2

jay.sf
jay.sf

Reputation: 73692

You may use 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"   

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389265

We can use 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"     

Upvotes: 1

Related Questions