我的情况是这样的:
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
....有什么想法吗?唐克斯。
发布于 2012-10-24 03:17:32
这是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的答案。去接受那个吧。
发布于 2012-10-24 03:28:07
table函数不起作用吗?
> with(DF, table(List, Count))
Count
List 1 2
R472 2 2
R845 1 2更新:根据布兰登的评论,如果你不喜欢使用with,这也是可行的
> table(DF$List, DF$Count)发布于 2012-10-24 03:18:07
我认为有一种更有效的方法,但这里有一个想法
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 2https://stackoverflow.com/questions/13037449
复制相似问题