R - 从数据框中剪切数据以平衡它

时间:2016-06-12 21:33:59

标签: r dataframe balance

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

enter image description here

我想删除一个因子中少于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
}

enter image description here

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

2 个答案:

答案 0 :(得分:2)

使用data.table

的选项
library(data.table)
res <- setDT(images)[, if(.N > = 5) head(.SD, 5) , by = V1]

答案 1 :(得分:1)

使用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, ...

您可以将结果分配给正常的对象。例如function updateQty() { var Qty = document.getElementById('quantity'); var vshowCost = document.getElementById('showCost'); var vpostCost = document.getElementById('postCost'); vshowCost.value = parseFloat(Qty.value)*100; vpostCost.value = parseFloat(Qty.value)*100; }