我可以使用什么数据结构来存储一些数据表并使用R中的字典之类的键?

时间:2022-12-08 13:01:50

Lets say I have 2 data tables:

假设我有2个数据表:

data_table1
data_table2

I want to be able to store them in a structure and with keys pointing to them so that I can easily extract them as needed.

我希望能够将它们存储在一个结构中,并使用指向它们的键,以便我可以根据需要轻松地提取它们。

'data_table1' is the key for datatable1

for e.g.

例如

How do I do this in R and what structure should I use?

我如何在R中执行此操作以及应该使用哪种结构?

1 个解决方案

#1


1  

To elaborate on ilir's suggestion with an example, if you have two differently structured data.frames, you can use a list like so:

要通过示例详细说明ilir的建议,如果您有两个不同结构的data.frames,您可以使用如下列表:

df1 <- data.frame(id = 1:5, data = runif(5))
df2 <- data.frame(id = 1:3, data = sample(letters, 3))

alldata <- list(data_table1 = df1, data_table2 = df2)

alldata$data_table1 # access df1
alldata$data_table2 # access df2

If your data frames have the same structure, you could combine them for example with an extra key column (here table) like so:

如果您的数据框具有相同的结构,您可以将它们组合在一起,例如使用额外的键列(此处为表格),如下所示:

df1 <- data.frame(table = "data_table1", id = 1:5, data = runif(5))
df2 <- data.frame(table = "data_table2", id = 1:3, data = runif(3))

alldata <- rbind(df1, df2)

subset(alldata, table == "data_table1") # access df1
subset(alldata, table == "data_table2") # access df2

#1


1  

To elaborate on ilir's suggestion with an example, if you have two differently structured data.frames, you can use a list like so:

要通过示例详细说明ilir的建议,如果您有两个不同结构的data.frames,您可以使用如下列表:

df1 <- data.frame(id = 1:5, data = runif(5))
df2 <- data.frame(id = 1:3, data = sample(letters, 3))

alldata <- list(data_table1 = df1, data_table2 = df2)

alldata$data_table1 # access df1
alldata$data_table2 # access df2

If your data frames have the same structure, you could combine them for example with an extra key column (here table) like so:

如果您的数据框具有相同的结构,您可以将它们组合在一起,例如使用额外的键列(此处为表格),如下所示:

df1 <- data.frame(table = "data_table1", id = 1:5, data = runif(5))
df2 <- data.frame(table = "data_table2", id = 1:3, data = runif(3))

alldata <- rbind(df1, df2)

subset(alldata, table == "data_table1") # access df1
subset(alldata, table == "data_table2") # access df2