Ho due colonne nel frame dei dati
2010 1 2010 1 2010 2 2010 2 2010 3 2011 1 2011 2
Voglio contare la frequenza di entrambe le colonne e ottenere il risultato in questo formato
ym Freq 2010 1 2 2010 2 2 2010 3 1 2011 1 1 2011 2 1
Se i tuoi dati sono dataframe df
con colonne y
ed m
library(plyr) counts <- ddply(df, .(df$y, df$m), nrow) names(counts) <- c("y", "m", "Freq")
Non ho ancora visto una risposta dplyr . Il codice è piuttosto semplice.
library(dplyr) rename(count(df, y, m), Freq = n) # Source: local data frame [5 x 3] # Groups: V1 [?] # # ym Freq # (int) (int) (int) # 1 2010 1 2 # 2 2010 2 2 # 3 2010 3 1 # 4 2011 1 1 # 5 2011 2 1
Dati:
df <- structure(list(y = c(2010L, 2010L, 2010L, 2010L, 2010L, 2011L, 2011L), m = c(1L, 1L, 2L, 2L, 3L, 1L, 2L)), .Names = c("y", "m" ), class = "data.frame", row.names = c(NA, -7L))
Una versione data.table più idiomatica della risposta di @ ugh sarebbe:
library(data.table) # load package df <- data.frame(y = c(rep(2010, 5), rep(2011,2)), m = c(1,1,2,2,3,1,2)) # setup data dt <- data.table(df) # transpose to data.table dt[, list(Freq =.N), by=list(y,m)] # use list to name var directly
Se avevi un frame di dati molto grande con molte colonne o non conoscevi i nomi delle colonne in anticipo, qualcosa di simile potrebbe essere utile:
library(reshape2) df_counts <- melt(table(df)) names(df_counts) <- names(df) colnames(df_counts)[ncol(df_counts)] <- "count" df_counts ym count 1 2010 1 2 2 2011 1 1 3 2010 2 2 4 2011 2 1 5 2010 3 1 6 2011 3 0
Utilizzando sqldf
:
sqldf("SELECT y, m, COUNT(*) as Freq FROM table1 GROUP BY y, m")
library(data.table) oldformat <- data.table(oldformat) ## your orignal data frame newformat <- oldformat[,list(Freq=length(m)), by=list(y,m)]