我在数据框中有两列
2010 1
2010 1
2010 2
2010 2
2010 3
2011 1
2011 2
我想计算两列的频率并以此格式获得结果
y m Freq
2010 1 2
2010 2 2
2010 3 1
2011 1 1
2011 2 1
答案 0 :(得分:30)
如果您的数据是包含df
列和y
m
library(plyr)
counts <- ddply(df, .(df$y, df$m), nrow)
names(counts) <- c("y", "m", "Freq")
答案 1 :(得分:10)
我还没有看到 dplyr 的答案。代码很简单。
library(dplyr)
rename(count(df, y, m), Freq = n)
# Source: local data frame [5 x 3]
# Groups: V1 [?]
#
# y m Freq
# (int) (int) (int)
# 1 2010 1 2
# 2 2010 2 2
# 3 2010 3 1
# 4 2011 1 1
# 5 2011 2 1
数据:强>
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))
答案 2 :(得分:7)
@ ugh的答案更为惯用的data.table版本是:
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
答案 3 :(得分:4)
使用sqldf
:
sqldf("SELECT y, m, COUNT(*) as Freq
FROM table1
GROUP BY y, m")
答案 4 :(得分:4)
如果你有一个包含很多列的非常大的数据框或者事先不知道列名,那么这样的东西可能会有用:
library(reshape2)
df_counts <- melt(table(df))
names(df_counts) <- names(df)
colnames(df_counts)[ncol(df_counts)] <- "count"
df_counts
y m 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
答案 5 :(得分:3)
library(data.table)
oldformat <- data.table(oldformat) ## your orignal data frame
newformat <- oldformat[,list(Freq=length(m)), by=list(y,m)]
答案 6 :(得分:1)
这是使用R
和table()
的简单基础as.data.frame()
解决方案
df2 <- as.data.frame(table(df1))
# df2
y m Freq
1 2010 1 2
2 2011 1 1
3 2010 2 2
4 2011 2 1
5 2010 3 1
6 2011 3 0
df2[df2$Freq != 0, ]
# output
y m Freq
1 2010 1 2
2 2011 1 1
3 2010 2 2
4 2011 2 1
5 2010 3 1
数据
df1 <- 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))