【问题标题】:R - cut data from data frame to balance itR - 从数据帧中剪切数据以平衡它
【发布时间】:2016-06-12 21:33:58
【问题描述】:

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

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

数据集构建如下:

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]) 时,然后执行操作以修剪数据集。 我真的不知道如何从这里开始,感谢任何帮助

【问题讨论】:

  • 我知道您的数据并不小,但为了写出一个可重现的好问题,这将使您获得支持和答案,请包括可重现的,我们可以复制和粘贴以重现您的数据/问题并重现您的问题。您可以使用内置数据集或创建自己的数据集并包含您使用的代码。
  • 好吧,我尽力让它可重现,但仍然需要数据集,它是公开可用的,但下载速度很慢

标签: r dataframe balance


【解决方案1】:

使用data.table的选项

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

【讨论】:

  • 这似乎有效(将数据集从 2639 -> 1090 个对象减少)。谢谢!
  • 也许你可以告诉我为什么plot(res$V1)在那之后工作,但是plot(res[1])给出一个错误:Error in plot.new() : figure margins too large?不应该一样吗?
  • @4ndro1d data.table 中的子集列略有不同 res$V1 是一个向量。您可以使用res[[1]] 获取第一列作为向量
【解决方案2】:

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

【讨论】:

  • 我必须将结果分配给某个变量吗?我试过了,我没有得到任何结果。数据框既没有改变,我也不能将某些东西存储到变量中。但它看起来很像我正在寻找的东西。
  • 当分配给这样的变量时:res1 &lt;- group_by(images, V1) %&gt;% # group by the V1 column filter(n() &gt;= 5) %&gt;% # keep only groups with 5 or more rows slice(1:5) %&gt;% 变量 res1 甚至没有在我的工作区中创建
  • 哦,最后我还有一个额外的管道。大概就是这样。现已删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 2013-07-24
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
相关资源
最近更新 更多