将因子级别转换为列名称

时间:2015-01-16 11:52:46

标签: r dataframe

假设我有以下数据集(命名数据集):

id  type    count
1   typeA   10
1   typeB   20
1   typeC   30
2   typeA   15
2   typeB   15
3   typeC   20

下面将会产生R代码:

id  type_A  type_B  type_C
1   10       20       30
2   15       15       na
3   na       na       20

1 个答案:

答案 0 :(得分:5)

您可以使用tidyr

library(tidyr)
spread(dat, type, count)

#   id typeA typeB typeC
# 1  1    10    20    30
# 2  2    15    15    NA
# 3  3    NA    NA    20

其中dat是数据框的名称。

相关问题