假设我有这个R数据框:
ts year month day
1 1295234818000 2011 1 17
2 1295234834000 2011 1 17
3 1295248650000 2011 1 17
4 1295775095000 2011 1 23
5 1296014022000 2011 1 26
6 1296098704000 2011 1 27
7 1296528979000 2011 2 1
8 1296528987000 2011 2 1
9 1297037448000 2011 2 7
10 1297037463000 2011 2 7
dput(a)
structure(list(ts = c(1295234818000, 1295234834000, 1295248650000,
1295775095000, 1296014022000, 1296098704000, 1296528979000, 1296528987000,
1297037448000, 1297037463000), year = c(2011, 2011, 2011, 2011,
2011, 2011, 2011, 2011, 2011, 2011), month = c(1, 1, 1, 1, 1,
1, 2, 2, 2, 2), day = c(17, 17, 17, 23, 26, 27, 1, 1, 7, 7)), .Names = c("ts",
"year", "month", "day"), row.names = c(NA, 10L), class = "data.frame")
有没有办法创建数据框架的向量,其中每个都是原始的子集,具有年,月,日组合的唯一分组?理想情况下,我想按顺序取回数据帧DF1,DF2,DF3,DF4,DF5和DF6,其中:
DF1:
ts year month day
1 1295234818000 2011 1 17
2 1295234834000 2011 1 17
3 1295248650000 2011 1 17
DF2:
4 1295775095000 2011 1 23
DF3:
5 1296014022000 2011 1 26
DF4:
6 1296098704000 2011 1 27
DF5:
7 1296528979000 2011 2 1
8 1296528987000 2011 2 1
DF6:
9 1297037448000 2011 2 7
10 1297037463000 2011 2 7
任何帮助都将不胜感激。
答案 0 :(得分:3)
df <- df[order(df$year, df$month, df$day), ]
df.list <- split(df, list(df$year, df$month, df$day), drop=TRUE)
listnames <- setNames(paste0("DF", 1:length(df.list)), sort(names(df.list)))
names(df.list) <- listnames[names(df.list)]
list2env(df.list, envir=globalenv())
# > DF1
# ts year month day
# 1 1.295235e+12 2011 1 17
# 2 1.295235e+12 2011 1 17
# 3 1.295249e+12 2011 1 17
# > DF6
# ts year month day
# 9 1.297037e+12 2011 2 7
# 10 1.297037e+12 2011 2 7
修改强>
正如@thelatemail建议的那样,通过在split
中正确排序,可以更轻松地实现相同目标:
df.list <- with(df, split(df, list(day,month,year), drop=TRUE))
df.list <- setNames(df.list, paste0("DF",seq_along(df.list)))
list2env(df.list, envir=globalenv())