【问题标题】:Create vector of data frame subsets based on group by of columns根据列的分组创建数据框子集的向量
【发布时间】:2014-03-20 15:13:48
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

  • 当天使用拆分功能。看看这篇文章:stackoverflow.com/a/16038343/3248346
  • 另外,interaction 如果我正确理解您的需求,可能会有用。类似于split(a, interaction(a$year, a$month, a$day, drop = T))
  • @alexis_laz - drop=TRUE 也可以作为参数直接传递给split,所以这也可以:with(a, split(a, list(year,month,day), drop=TRUE))

标签: r vector dataframe


【解决方案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 中正确排序可以更轻松地归档:

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

【讨论】:

  • 不需要所有的排序,只需在split - df.list &lt;- with(a, split(a, list(day,month,year), drop=TRUE)) 中更改顺序,然后按顺序命名它们 - setNames(df.list,paste0("DF",seq_along(df.list)))
猜你喜欢
  • 2019-01-22
  • 2016-09-15
  • 1970-01-01
  • 2020-07-13
  • 2011-09-10
  • 2021-04-23
  • 1970-01-01
  • 2021-09-29
  • 2020-08-04
相关资源
最近更新 更多