将两列转换为矩阵形式

时间:2016-10-13 21:02:01

标签: r matrix

我有两列我想要转换为包含二进制文件作为其内容的矩阵。例如:

如果这些是列(姓名和动物):

Name  Animal  
Jen   Cat
Sam   Dog
Pat   Hamster
Ann   Fish
Lea   Cat
Jen   Hamster 
Sam   Hamster 
Jen   Fish 

我想将其转换为这种格式:

    Cat Dog Hamster Fish  
Jen  1  0   1        1
Sam  0  1   1        0
Pat  0  0   1        0
Ann  0  0   0        1
Lea  1  0   0        0

1 个答案:

答案 0 :(得分:0)

@ zx8754在评论中提到的table以外的内容:

table(df$Name, df$Animal)

您还可以使用xtabs,如下所示:

xtabs(Col~Name+Animal, cbind(df,Col=1))

#     Animal
#Name  Cat Dog Fish Hamster
#  Ann   0   0    1       0
#  Jen   1   0    1       1
#  Lea   1   0    0       0
#  Pat   0   0    0       1
#  Sam   0   1    0       1

数据

df <- structure(list(Name = structure(c(2L, 5L, 4L, 1L, 3L, 2L, 5L, 
2L), .Label = c("Ann", "Jen", "Lea", "Pat", "Sam"), class = "factor"), 
    Animal = structure(c(1L, 2L, 4L, 3L, 1L, 4L, 4L, 3L), .Label = c("Cat", 
    "Dog", "Fish", "Hamster"), class = "factor")), .Names = c("Name", 
"Animal"), class = "data.frame", row.names = c(NA, -8L))