首页 > 解决方案 > 基于条件的有效观察

问题描述

我有以下数据框。

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)

任何帮助表示赞赏。

标签: r

解决方案


推荐阅读