我有一个名为PX557.GGH.WXWX.4986746(示例)的对象。
此对象的前5个字符对此对象是唯一的。
如何从前5个字符调用此对象,而不是重命名?
我可以添加到PX557末尾的某个字符,它会调用此对象吗?
由于
答案 0 :(得分:1)
我们可以使用get
函数,并对ls
返回的字符向量执行一些操作:
# create some arbitrary objects
aaa_bbb_ccc <- 'foo'; bbb_ccc_aaa <- 'haz'; ccc_bbb_aaa <- 'mat'
# use substring on ls
get(ls()[substring(ls(), 1, 3) == 'aaa'])
[1] "foo"
答案 1 :(得分:0)
Might be overkill, but here's a helper function that searches for an object using the first few letters, and returns the value if it finds a unique object:
rm(list = ls())
g <- function(x) {
x <- deparse(substitute(x))
y <- grep(paste0("^", x), ls(envir = globalenv()), value = TRUE)
if (length(y) > 1) {
return(message("More than 1 match"))
} else {
tryCatch(
get(y, envir = globalenv()),
error = function(e) message(paste(x, "not found"))
)
}
}
PX557.GGH.WXWX.4986746 <- 123
AB123.GGH.WXWX.4986746 <- 456
PX556.FFG.JKJK.1234567 <- 789
g(PX557)
# [1] 123
g(AB123)
# [1] 456
g(AB1)
# [1] 456
g(AB999)
# AB999 not found
g(PX)
# More than 1 match