在R中的数据帧上迭代行比较

时间:2015-03-20 14:00:45

标签: r

我正在尝试比较学生测试答案中的相似之处。因此,对于学生A,B,C和D,我想比较每对可能的学生有多少次有相同的答案。例如,A& B回答了同样的5/7个问题,A& C回答了4/7个问题,等等。我最终只得到一列,其中行反映了每一对。

以下是一个示例数据框:

      Student Q1 Q2 Q3 Q4 Q5
      A       1  3  2  4  1
      B       1  2  4  1  1
      C       2  4  4  2  1
      D       3  1  2  3  4
      E       3  3  1  2  1

到目前为止,我已经使用combn设置了对:

    test<-combn(Book1$Student,2)
    compare<-lapply(1:ncol(test), function(x) rbind(Book1[Book1$Student==test[1,x], ],
                                   Book1[Book1$Student==test[2,x], ]))

这会生成一个包含唯一比较的列表,但我无法弄清楚如何在行之间对相同的响应求和。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

你可以使用combn

combn(1:nrow(Book1), 2, function(indices){
  sum(Book1[indices[1], 2 : 6] == Book1[indices[2], 2 : 6])
})

答案 1 :(得分:0)

从宽格式到长格式重塑var webpack = require('webpack'); var definePlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true')), __PRERELEASE__: JSON.stringify(JSON.parse(process.env.BUILD_PRERELEASE || 'false')) }); var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js'); module.exports = { cache: true, entry: { main: './views/index.jsx' }, output: { path: 'public/build', filename: '[name].js' }, module: { loaders: [ {test: /\.jsx?$/, loader: 'babel', exclude: /(node_modules|bower_components)/, query: { presets: ['react', 'es2015'] }}, ] }, resolve: { extensions: ['', '.js', '.jsx'] }, plugins: [ definePlugin, commonsPlugin ] }; 后,可以使用自联接解决此问题:

Book1
library(data.table)
long <- melt(setDT(Book1)[
  , Student := ordered(Student)], id.vars = "Student")
long[long, on = .(variable, value)][
  , .N, by = .(Student, i.Student)][
    Student < i.Student][
      order(Student, i.Student)]

或者,可以通过

返回任意两个学生之间具有相同答案数量的对称矩阵
   Student i.Student N
1:       A         B 2
2:       A         C 1
3:       A         D 1
4:       A         E 2
5:       B         C 2
6:       B         E 1
7:       C         E 2
8:       D         E 1
long <- melt(setDT(Book1), id.vars = "Student")
dcast(long[long, on = .(variable, value)][, .N, by = .(Student, i.Student)], 
      Student ~ i.Student, fill = 0)