R 如何在数据帧中按列减少行数?

R 如何在数据帧中按列减少行数?,r,dataframe,R,Dataframe,示例数据: dept category quantity price 1 r s t 1 . 1 . . 1 1 1 2 2 2 2 . 2 . 2 3 3 3 3 . . . 我想按照以下方式减少每个“dept”列的行数:

示例数据:

  dept    category   quantity  price
  1         r           s        t    
  1         .
  1         .           .
  1
  1
  1
  2
  2
  2
  2         .
  2         .
  2
  3
  3
  3
  3         .           .        .
我想按照以下方式减少每个“dept”列的行数:

  if(dept == 1) keep only 2 rows
  if(dept == 2) keep only 4 rows
  if(dept == 3) keep only 3 rows
最终的数据帧应如下所示:

dept    category   quantity  price
  1         r           s        t    
  1         .
  2
  2
  2
  2         .
  3
  3
  3

如何轻松做到这一点?

一种方法是使用plyr。首先制作一个矩阵,显示每个dept值要保留多少行,例如
a不使用任何附加包的另一种方式:

df <- data.frame(dept=c(rep(1:3, each=5)), # exemplary data.frame
                 data=sample(letters, 15, replace=TRUE))
rows_to_keep <- c(2, 4, 3)
do.call(rbind, lapply(split(df, df$dept), function(subdf)
   subdf[seq_len(rows_to_keep[subdf$dept[1]]),]))
df
df <- data.frame(dept=c(rep(1:3, each=5)), # exemplary data.frame
                 data=sample(letters, 15, replace=TRUE))
rows_to_keep <- c(2, 4, 3)
do.call(rbind, lapply(split(df, df$dept), function(subdf)
   subdf[seq_len(rows_to_keep[subdf$dept[1]]),]))