问题描述
给出排名问题的输出:
... filter(all(c('a','b') %in% letter) & n_distinct(letter) == 2)
## another alternative
... filter(all(c('a','b') %in% letter) & all(letter %in% c('a','b')))
我想计算每个字母的等级分数=每个字母的等级数*每个等级的权重(等级1 = 5分,等级2 = 4分,...,等级5 = 1分)/总响应数。
我要使用字母来获取每个等级的计数:
df <- structure(list(rank1 = c("A","NA","C","B","A"),rank2 = c("B","A","B"),rank3 = c("C","NA"),rank4 = c("D","E","D",rank5 = c("E","NA")),.Names = c("rank1","rank2","rank3","rank4","rank5"),class = "data.frame",row.names = c("1","2","3","4","5"))
rank1 rank2 rank3 rank4 rank5
1 A B C D E
2 NA NA NA NA NA
3 C A B E D
4 B A C D E
5 A B NA NA NA
所以现在我想计算每个字母的分数(例如A =(2 * 5 + 2 * 4)/ 4) 我不知道如何计算总响应数,然后如何创建一个函数来计算排名得分。
解决方法
使用Apply函数,您可以遍历表格的每一行,然后计算得分
apply(table(unlist(df),c(col(df))),1,FUN = function(row){
return((row[1] * 5 + row[2] * 4 + row[3] * 3 + row[4] * 2 + row[5] * 1) / sum(row))
})
A B C D E NA
4.500000 4.000000 3.666667 1.666667 1.333333 2.625000
apply函数的有趣部分将整个行传递给该函数,然后只是将行中每个对应元素乘以权重,然后除以该行的受访者总数的情况