R中的DataFrame转换

时间:2016-07-03 08:46:32

标签: r dataframe

我在R中有下一个DataFrame:

col1 col2 col3
a    W    1
a    Q    1
b    T    2
b    W    3
b    Q    1
b    Z    2
c    T    3
c    Z    1
....

我想在下一个数据框中对其进行转换

col1 T W Q Z
a    0 1 1 0
b    2 3 1 2
c    3 0 0 1
...

在R中执行此操作的最有效方法是什么?

2 个答案:

答案 0 :(得分:2)

$scope.init()

如果我们想要准确匹配预期的输出(除了没有看起来具有模式AFAICT的列顺序):

reshape(df,dir='w',idvar='col1',timevar='col2');
##   col1 col3.W col3.Q col3.T col3.Z
## 1    a      1      1     NA     NA
## 3    b      3      1      2      2
## 7    c     NA     NA      3      1

答案 1 :(得分:2)

我们可以使用dcast中的data.table转换为'范围'格式。

library(data.table)
dcast(setDT(df1), col1~col2, value.var='col3', fill = 0)
#   col1 Q T W Z
#1:    a 1 0 1 0
#2:    b 1 2 3 2
#3:    c 0 3 0 1

或另一个选项是spread

library(tidyr)
spread(df1, col2, col3, fill=0)    
#  col1 Q T W Z
#1    a 1 0 1 0
#2    b 1 2 3 2
#3    c 0 3 0 1