创建中的R的频率表(Creating a frequency table in R)

2019-10-21 03:38发布

我是新来的R,我想创建一个频率表,我有一个数据就是这样,

Member_id                   Car                 interest
1                    FORD_MUSTANG                 4
1                    BUICK_Lucerne                1
1                    CHEVROLET_SILVERADO          1
2                    CHEVROLET_SILVERADO          1
2                    FORD_MUSTANG                 2  
3                    FORD_MUSTANG                 6

我想有这样一个频率表:

MEmber_id       FORD_MUSTANG   BUICK_Lucerne   CHEVROLET_SILVERADO
1                  4             1               1
2                  2             0               1
3                  6             0               0

我一直在使用表(Member_id,汽车)试过了,但它返回值我1个值为每个汽车品牌。

感谢所有帮助。

Answer 1:

尝试

library(reshape2) 
dcast(df, Member_id~Car, value.var="interest", fill=0)
#    Member_id BUICK_Lucerne CHEVROLET_SILVERADO FORD_MUSTANG
#1         1             1                   1            4
#2         2             0                   1            2
#3         3             0                   0            6

要么

library(tidyr) 
spread(df, Car, interest, fill=0)
#  Member_id BUICK_Lucerne CHEVROLET_SILVERADO FORD_MUSTANG
#1         1             1                   1            4
#2         2             0                   1            2
#3         3             0                   0            6

如果你想创建的顺序列您指定

 df$Car <- with(df, factor(Car, unique(Car)))
 spread(df, Car, interest, fill=0)
#  Member_id FORD_MUSTANG BUICK_Lucerne CHEVROLET_SILVERADO
#1         1            4             1                   1
#2         2            2             0                   1
#3         3            6             0                   0

数据

 df <- structure(list(Member_id = c(1L, 1L, 1L, 2L, 2L, 3L), Car = c("FORD_MUSTANG", 
 "BUICK_Lucerne", "CHEVROLET_SILVERADO", "CHEVROLET_SILVERADO", 
 "FORD_MUSTANG", "FORD_MUSTANG"), interest = c(4L, 1L, 1L, 1L, 
 2L, 6L)), .Names = c("Member_id", "Car", "interest"), class = "data.frame", row.names = c(NA, 
-6L))


文章来源: Creating a frequency table in R
标签: r frequency