在 R 中使用正则表达式为变量赋值 [英] Assign names to variable using regular expression in R
本文介绍了在 R 中使用正则表达式为变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我的工作区中有一堆变量.我想将它们的一个子集分配给一个新变量,这样我就可以轻松地在这个子集上运行函数:
So I have a bunch of variables in my workspace. I want to assign a subset of them to a new variable, so I can easily run functions on this subset:
工作区:
...
group10
group40
location40
test
期望的分配:
groupList <- list(group10,group40, ...)
预期的正则表达式:
^group[0-9]+
有什么想法吗?
推荐答案
ls
接受一个 pattern
参数:
group10 <- group40 <- location40 <- test <- NA
mysub <- ls(pattern="^group[0-9]+")
mysub
#[1] "group10" "group40"
您可以使用 lapply
循环遍历变量名称列表并获取
它们的值
You can use lapply
to loop over the list of variable names and get
their values
groupList <- lapply(mysub, get)
或者,在一行中
groupList <- lapply(ls(pattern="^group[0-9]+"), get)
这篇关于在 R 中使用正则表达式为变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文