R 拉取全局环境中具有特定属性的所有对象

R 拉取全局环境中具有特定属性的所有对象,r,R,假设我有一个全局环境中的对象列表。如何仅提取具有特定属性集的属性 x1 <- 1:10 x2 <- 1:10 x3 <- 1:10 x4 <- 1:10 x5 <- 1:10 attr(x1, "foo") <- "bar" attr(x5, "foo") <- "bar" x1这里有一种方法 # collect all objects in global environment all = lapply(ls(), get) # extract

假设我有一个全局环境中的对象列表。如何仅提取具有特定属性集的属性

x1 <- 1:10
x2 <- 1:10
x3 <- 1:10
x4 <- 1:10
x5 <- 1:10 

attr(x1, "foo") <- "bar"
attr(x5, "foo") <- "bar"

x1这里有一种方法

# collect all objects in global environment
all = lapply(ls(), get)

# extract objects with attribute = "bar"
bar = all[lapply(all, attr, "foo") == "bar"]

Ramnath答案的几个变体

对于获取多个对象,最好使用
mget
而不是
get
lappy

all <- mget(ls(), envir = globalenv())
Filter(function(x) attr(x, "foo") == "bar", all)