2012-10-23 111 views
1

我有这样的情况:
DF频率计数

List  Count 
R472  1 
R472  1 
R472  2 
R472  2  
R845  1 
R845  2 
R845  2 
....  ... 

我想下面的输出:

DF

List   freq_of_number1 freq_of_number2 
R472     2     2 
R845     1     2 
.... 

任何想法? Thnks。

回答

4

这是aggregate工作:

d <- read.table(text="List  Count 
R472  1 
R472  1 
R472  2 
R472  2  
R845  1 
R845  2 
R845  2", header=TRUE) 

aggregate(Count ~ List, data=d, FUN=table) 

# List Count.1 Count.2 
# 1 R472  2  2 
# 2 R845  1  2 

编辑:

上面的代码在你提供的情况下,因为你已经接受了答案,我认为它的工作原理为您较大的情况下同样,但如果List中的任何条目缺少Count中的某个数字,则此简单答案将会失败。对于更一般的情况:

DF <- read.table(text="List  Count 
R472  1 
R472  1 
R472  2 
R472  2  
R845  1 
R845  2 
R845  2 
R999  2", header=TRUE) 

f <- function(x) { 
    absent <- setdiff(unique(DF$Count), x) 
    ab.count <- NULL 
    if (length(absent) > 0) { 
     ab.count <- rep(0, length(absent)) 
     names(ab.count) <- absent 
    } 
    result <- c(table(x), ab.count) 
    result[order(names(result))] 
} 
aggregate(Count ~ List, data=d, FUN=f) 

# List Count.1 Count.2 
# 1 R472  2  2 
# 2 R845  1  2 
# 3 R999  0  1 

编辑2:

刚看到@ JasonMorgan的答案。去接受那个。

+0

很好的解决方案:d +1 –

+0

mplourde嗨!再次感谢! – Bnf8

2

我认为有一种更有效的方式来做到这一点,但这里有一个想法

DF <- read.table(text='List  Count 
R472  1 
R472  1 
R472  2 
R472  2  
R845  1 
R845  2 
R845  2', header=TRUE) 



Freq <- lapply(split(DF, DF$Count), function(x) aggregate(.~ List, data=x, table)) 
counts <- do.call(cbind, Freq)[, -3] 
colnames(counts) <- c('List', 'freq_of_number1', 'freq_of_number2') 
counts 
List freq_of_number1 freq_of_number2 
1 R472    2    2 
2 R845    1    2 
3

table功能不起作用?

> with(DF, table(List, Count)) 
     Count 
List 1 2 
    R472 2 2 
    R845 1 2 

更新:每布兰登的评论,这也能发挥作用,如果你不喜欢使用with

> table(DF$List, DF$Count) 
+0

+1这是正确的方法 –

+1

'table()'是你所需要的。 '与'是不必要的。 –