1

I would like to build a R object .rda or simply a list object to contain several data frames. Then in each data frame I am going to add a small description of the file in the attribute. Now my question is that is it possible to search the particular object to find the data frame which contains a particular string?

For example, I would like to search the string "inflation" to see which data frame has "inflation" attribute in the object.

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.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"
于 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 に答える