如何在R中基于随机因子lk修改数据的statue字段
R语言实现statue字段动态修改方案
实现思路
- 统计当前
t状态的记录数:先计算数据框中statue为t的总条数,记为current_t - 分两种逻辑处理:
- 当
lk > current_t时:计算需要从n转为t的数量(lk - current_t),筛选出statue为n的记录,按cost升序排序,取前N条将statue改为t - 当
lk <= current_t时:计算需要从t转为n的数量(current_t - lk),筛选出statue为t的记录,按salary降序排序,取前N条将statue改为n
- 当
代码实现
1. 构造示例数据框
# 还原你提供的示例数据 df <- data.frame( statue = c("t", "n", "n", "n", "t", "n", "t", "t", "n", "t"), cost = c(43, 5, 27, 26, 39, 12, 42, 38, 39, 25), salary = c(21, 17, 21, 35, 38, 22, 13, 32, 15, 38) )
2. 核心处理函数
update_statue <- function(df, lk) { current_t <- sum(df$statue == "t") if (lk > current_t) { # 计算需要新增的t数量 need_add <- lk - current_t # 筛选statue为n的行,按cost升序取前need_add条的索引 n_rows <- which(df$statue == "n") sorted_n <- n_rows[order(df$cost[n_rows])] target_idx <- sorted_n[1:need_add] df$statue[target_idx] <- "t" } else if (lk <= current_t) { # 计算需要移除的t数量 need_remove <- current_t - lk # 筛选statue为t的行,按salary降序取前need_remove条的索引 t_rows <- which(df$statue == "t") sorted_t <- t_rows[order(-df$salary[t_rows])] target_idx <- sorted_t[1:need_remove] df$statue[target_idx] <- "n" } return(df) }
3. 测试示例
测试lk=7的情况(当前t数量为5)
result_lk7 <- update_statue(df, lk=7) print(result_lk7)
输出结果中,原第2、6条(cost最小的两个n)的statue会被改为t
测试lk=3的情况(当前t数量为5)
result_lk3 <- update_statue(df, lk=3) print(result_lk3)
输出结果中,原第5、10条(salary最大的两个t)的statue会被改为n
内容的提问来源于stack exchange,提问作者mike_44
相关产品推荐
相关产品推荐

