1

我想构建一个 R 对象 .rda 或只是一个列表对象来包含多个数据框。然后在每个数据框中,我将在属性中添加文件的小描述。现在我的问题是是否可以搜索特定对象以找到包含特定字符串的数据框?

例如,我想搜索字符串“inflation”以查看对象中哪个数据框具有“inflation”属性。

4

2 回答 2

2

@sebastian-c 的答案是正确的,但这可能不是您想要做的。下面是一个例子:

set.seed(123)
data1 <- data.frame(x=rnorm(5), y=rnorm(5))
data2 <- data.frame(x=rnorm(5), y=rnorm(5))
data3 <- data.frame(x=rnorm(5), wowie=rnorm(5))

data1
#             x          y
# 1 -0.56047565  1.7150650
# 2 -0.23017749  0.4609162
# 3  1.55870831 -1.2650612
# 4  0.07050839 -0.6868529
# 5  0.12928774 -0.4456620
A <- attributes(data1) # Let's store these attributes
attributes(data1) <- list(description="The first datum on inflation")
data1
# [[1]]
# [1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774
# 
# [[2]]
# [1]  1.7150650  0.4609162 -1.2650612 -0.6868529 -0.4456620
# 
# attr(,"description")
# [1] "The first datum on inflation"

哎呀!我们失去了所有原始属性!值得庆幸的是,我们可以恢复它们,因为我们已经保存了它们,然后尝试以不同的方式分配它们,使用attr().

attributes(data1) <- A # Good thing we stored those attributes!
attr(data1, "description") <- "The first datum on inflation"
data1
#             x          y
# 1 -0.56047565  1.7150650
# 2 -0.23017749  0.4609162
# 3  1.55870831 -1.2650612
# 4  0.07050839 -0.6868529
# 5  0.12928774 -0.4456620
attributes(data1)
# $names
# [1] "x" "y"
# 
# $row.names
# [1] 1 2 3 4 5
# 
# $class
# [1] "data.frame"
# 
# $description
# [1] "The first datum on inflation"

如果您想采用这种attributes(data1)方法,请记住属性是一个命名列表,因此您也可以像添加新项目到列表中一样添加属性。换句话说,这也有效:attributes(data1)$description <- "The first datum on inflation"


这行得通,所以对其他data.frames 做同样的事情:

attr(data2, "description") <- "The second datum on inflation"
attr(data3, "description") <- "The first datum on deflation"

现在,拼凑一个小功能来搜索所有属性。如果您只想搜索特定属性,则可以修改该函数。

findmyattr <- function(term, datasets) {
    temp <- setNames(lapply(datasets, function(x) unlist(attributes(get(x)))),
                     datasets)
    datasets[as.logical(colSums(sapply(temp, grepl, pattern = term)))]
}

以下是一些正在使用的函数的示例:

findmyattr("inflation", c("data1", "data2", "data3"))
# [1] "data1" "data2"
findmyattr("first", c("data1", "data2", "data3"))
# [1] "data1" "data3"
findmyattr("wowie", c("data1", "data2", "data3"))
# [1] "data3"
于 2013-01-10T09:44:00.913 回答
0

Sebastian,您编辑的代码可能存在以下问题

descriptions <- sapply(lis, function(x) unlist(attributes(get(x))))

这里的描述包括所有属性。结果,以下步骤

which_descriptions <- grep("inflation", descriptions)  

产生比确切文件号更大的数字。结果如下

lis[which_descriptions]

也不起作用。

于 2013-01-12T11:01:32.057 回答