r - 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.
解决方案
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")
推荐阅读
- visual-studio-2015 - Visual Studio 2015 在哪里存储其 Git 配置信息?
- python - 如何根据使用 Selenium 的 html 从使用 xpath 找到的元素中检索属性 aria-label 的值
- java - 如何分配字符串值并将其存储在 hashmap 中,然后单独检索它?
- javascript - 在 React Native 中从两个类传递数据
- gensim - 更新word2vec模型是否需要混合旧语料库和新语料库?
- php - 我无法注册我的数据库!据说 DoctrineServiceProvider 永远不会被更多使用
- react-native - 如何在没有 redux 的情况下在我的应用程序中使用 pjsip?
- r - r update.packages() 不更新由其他包导入的包
- sql-server - 无法连接到 AWS RDS - SQL Server
- javascript - 如何在 Sails.JS 中使用 Vue.JS 和 Vue-Resource?