搜索R对象的属性

时间:2013-01-10 06:30:22

标签: r search attributes

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

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

2 个答案:

答案 0 :(得分: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.frame s也一样:

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"

答案 1 :(得分:0)

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

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

此处的描述包括所有属性。因此,以下步骤

which_descriptions <- grep("inflation", descriptions)  
除了确切的文件编号之外,

产生的数字更大。结果如下

lis[which_descriptions]

也行不通。