r - 基于条件的有效观察
问题描述
我有以下数据框。
Student Class Jan_18_score Feb_18_score Jan_18_Weight Feb_18_Weight
(1) Adam 1 NA 2 150 153
(2) Char 1 5 7 30 60
(3) Fred 1 -7 8 NA 80
(4) Greg 1 2 NA 80 40
(5) Ed 2 1 2 60 80
对于每个月,要使观察有效,它必须同时具有分数和权重。否则,分数和权重都变为 0。
数据应该是这样的
Student Class Jan_18_score Feb_18_score Jan_18_Weight Feb_18_Weight
(1) Adam 1 o 2 0 153
(2) Char 1 5 7 30 60
(3) Fred 1 0 8 0 80
(4) Greg 1 2 NA 80 0
(5) Ed 2 1 2 60 80
我尝试了以下方法(如果您有帮助,谢谢)。但有些值没有被更改为零。
# Separate score and weight columns
score_cols <- grep("score_", names(temp))
weight_cols <- grep("weight_", names(temp))
valid <- is.na(temp[score_cols]) | is.na(temp[weight_cols])
然后我使用新的 DF 进行计算
temp2 <- aggregate(.~class, cbind(temp["class"], temp[score_cols] * temp[weight_cols]), sum)
任何帮助表示赞赏。
解决方案
推荐阅读
- javascript - 从 Vue 2 迁移到 Vue 3 后,SVG 动画 endEvent 未触发
- mysql - 如何使用 MySQL 分别对列进行计数和分组?
- r - 使用 t_map 包 R 绘制县边界
- scala - 是否可以将 Scala ZIO 中的效果提升到另一个有效的上下文中?
- python - 如何设置python数据框列长度的限制?
- django - Django - 为什么我从 Axios/AJAX 登录后没有通过身份验证?
- c# - 使用 Jenkins 和 Bridge.net 扩展构建 C# 项目
- python - Append() 指令在 python 中不起作用
- highcharts - 反向链接图 - Highcharts
- python - 防止 Python 中的 for 循环用于求和函数