根据数据框中的其他变量计算变量的因子

Count factors of a variable depending of an other variable in a dataframe

我有一个 R 问题。我想根据数据框中的另一个变量计算一个变量的因子。

我举个例子:

我有

    ID   com
    125 nul
    125 nul
    125 dec
    125 asc
    125 0
    130 nul
    130 dec

我想要的

    ID|nul|dec|asc|0
    125|2|1|1|1
    130|1|1|0|0

注意:变量com是一个因子,ID是整数。

我尝试了我所知道的简单方法:table(df$ID, df$com) 但没有奏效。

你可以试试dcast

library(reshape2)
dcast(df,ID~com, value.var='com', length)
#   ID nul dec asc 0
#1 125   2   1   1 1
#2 130   1   1   0 0

或者直接使用table

 table(df)
 #    nul dec asc 0
 #125   2   1   1 1
 #130   1   1   0 0

数据

df <- structure(list(ID = c(125L, 125L, 125L, 125L, 125L, 130L, 130L
 ), com = structure(c(1L, 1L, 2L, 3L, 4L, 1L, 2L), .Label = c("nul", 
"dec", "asc", "0"), class = "factor")), .Names = c("ID", "com"
), row.names = c(NA, -7L), class = "data.frame")