在R中创建频率表 [英] Creating a frequency table in R

查看:65
本文介绍了在R中创建频率表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to R, I want to create a frequency table, I have a data like this,

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

我想要一个频率表,如下所示:

I would like to have a frequency table like this:

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

我尝试使用table(Member_id,car),但对于每个汽车品牌,它都会向我返回值1.

I have tried using table(Member_id,car), but it returns me values 1 values for each car make.

感谢任何帮助.

推荐答案

尝试

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

如果要按指定的顺序创建列

If you want to create the columns in the order you specified

 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))

这篇关于在R中创建频率表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆