从R中的数据帧创建稀疏矩阵

时间:2013-06-28 23:07:36

标签: r

给定一个数据框,其中有多个对象映射到同一个人:

mike toy
mike golf
mike swim
mike call
tom eat
tom sleep
nate eat

如何生成一个矩阵,其中包含每个元素的计数和其余的NA?:

     toy    golf   swim  call  eat  sleep 
mike 1      1        1     1    NA     NA
tom  NA     NA       NA    NA   1      1
nate NA     NA       NA    NA   1      NA

1 个答案:

答案 0 :(得分:1)

> df
    V1    V2
1 mike   toy
2 mike  golf
3 mike  swim
4 mike  call
5  tom   eat
6  tom sleep
7 nate   eat
> table(df)
      V2
V1     call eat golf sleep swim toy
  mike    1   0    1     0    1   1
  nate    0   1    0     0    0   0
  tom     0   1    0     1    0   0