0

我有一个包含 2600 个条目的数据框,这些条目分布在 249 个因子级别(人)中。数据集没有很好的平衡。

在此处输入图像描述

我想删除在一个因素中出现少于 5 次的所有条目。此外,我想将出现次数超过 5 次的数据减少到 5 次。所以最后我希望有一个整体条目较少的数据框,但在因素人上是平衡的。

数据集构建如下:

file_list <- list.files("path/to/image/folder", full.names=TRUE) 
# the folder contains 2600 images, which include information about the 
# person factor in their file name

file_names <- sapply(strsplit(file_list , split = '_'), "[",  1)
person_list <- substr(file_names, 1 ,3)
person_class <- as.factor(person_list)

imageWidth = 320; # uniform pixel width of all images
imageHeight = 280; # uniform pixel height of all images
variableCount = imageHeight * imageWidth + 2

images <- as.data.frame(matrix(seq(count),nrow=count,ncol=variableCount ))
images[1] <- person_class
images[2] <- eyepos_class

for(i in 1:count) {
  img <- readJPEG(file_list[i])
  image <- c(img)
  images[i, 3:variableCount] <- image
}

在此处输入图像描述

所以基本上我需要获取每个因子级别的样本数量(比如使用时summary(images[1])然后执行操作来修剪数据集。我真的不知道如何从这里开始,感谢任何帮助

4

2 回答 2

2

一个选项使用data.table

library(data.table)
res <- setDT(images)[, if(.N > = 5) head(.SD, 5) , by = V1]
于 2016-06-13T02:02:29.190 回答
1

使用dplyr

library(dplyr)
group_by(images, V1) %>%  # group by the V1 column
    filter(n() >= 5) %>%  # keep only groups with 5 or more rows
    slice(1:5)            # keep only the first 5 rows in each group

您可以将结果分配给正常的对象。例如my_desired_result = group_by(images, ...

于 2016-06-12T21:41:19.177 回答