2014-02-19 68 views
1

假设我有此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

使用当天的分裂功能。看看这篇文章:http://stackoverflow.com/a/16038343/3248346 –

+1

此外,'互动'可能是有用的,如果我明白你想要的东西正确。像'split(a,交互($ year,$ month,$ day,drop = T))''。 –

+2

@alexis_laz - 'drop = TRUE'也可以作为参数直接传递给'split',所以这也可以工作:'with(a,split(a,list(year,month,day),drop = TRUE ))' – thelatemail

回答

1
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正确排序来archieved简单:

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()) 
+0

不需要所有的排序,只需改变'split' - 'df.list < - 用(a,split(a,list(day,month,year),drop = TRUE))'然后的顺序按顺序命名 - setNames(df.list,paste0(“DF”,seq_along(df.list)))' – thelatemail

+0

@thelatemail好主意,谢谢。我做了一个编辑。 – lukeA

相关问题