我有几个数据框,每个数据框代表给定条件下的数据。
例如,df.1是在温度t1测量的数据,df.2在温度t2测量,依此类推。
我为每个数据框设置了属性温度,并将所有数据帧存储在列表中。
现在我想检索给定温度的数据帧。
所以我有两个问题:
是推荐的属性/列表方法吗?
有一种优雅的方法来检索适当温度的数据框吗?我看到了一种带有for循环的方法,但我想知道是否有更好的解决方案。
以下是一个示例代码:
x <- seq(0, 50, by = 0.1)
y1 <- sin(x)
y2 <- cos(x)
df.1 <- data.frame(time = x, value = y1)
attr(df.1, "Temperature") <- 20.0
df.2 <- data.frame(time = x, value = y2)
attr(df.2, "Temperature") <- 30.0
df.list <- list(df.1, df.2)
result <- NULL
for (df in df.list) {
if (attr(df, "Temperature") == 20) {
result <- df
}
}
答案 0 :(得分:0)
建议为您创建的列表提供适当的名称,例如
names(df.list) <- c("t20", "t30")
这样,您可以根据名称调出适当的表格,例如
head(df.list[["t20"]])
time value
1 0.0 0.00000000
2 0.1 0.09983342
3 0.2 0.19866933
4 0.3 0.29552021
5 0.4 0.38941834
6 0.5 0.47942554
head(df.list[["t30"]])
time value
1 0.0 1.0000000
2 0.1 0.9950042
3 0.2 0.9800666
4 0.3 0.9553365
5 0.4 0.9210610
6 0.5 0.8775826
答案 1 :(得分:0)
In the end, I chose JeremyS's solution: add a temperature column in the data frame.
x <- seq(0, 50, by = 0.1)
y1 <- sin(x)
y2 <- cos(x)
df.1 <- data.frame(time = x, value = y1, Temperature = 20.0)
df.2 <- data.frame(time = x, value = y2, Temperature = 30.0)
df.combined <- rbind(df.1, df.2)
result <- subset(df.combined, df.combined$Temperature == 20)
I don't really know what is the impact in terms of performance and memory cost, but R and ggplot seem to be designed for data frames rather than lists. Using a pure data frame approach thus seems the most convenient way.