gpt4 book ai didi

r - 如何重复火车组中少数类的行?

转载 作者:行者123 更新时间:2023-11-30 09:26:49 24 4
gpt4 key购买 nike

我想在我的火车集中重复少数群体类别的特定行。我知道,这不是一种非常奇特的工作方式,但我只是想尝试一下。

假设,我有这个数据框:

> df

group type number
1 class1 one 4
2 class1 three 10
3 class1 nine 3
4 class4 seven 9
5 class1 eight 4
6 class1 ten 2
7 class1 two 22
8 class4 eleven 8

现在我想多次重复我的少数类(class4)的行,以便在新的数据框中拥有 50% 的 class1 和 50% 的 class4。

我知道有函数rep,但我只能找到重复整个数据框的解决方案。

我该怎么做?

最佳答案

基础 R 方法

#Count frequency of groups
tab <- table(df$group)

#Count number of rows to be added
no_of_rows <- max(tab) - min(tab)

#count number of rows which are already there in the dataframe for the minimum group
existing_rows <- which(df$group %in% names(which.min(tab)))

#Add new rows
new_df <- rbind(df, df[rep(existing_rows,no_of_rows/length(existing_rows)), ])

#Check the count
table(new_df$group)

#class1 class4
# 6 6

关于r - 如何重复火车组中少数类的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52923840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com