分裂和表

时间:2012-11-02 16:26:43

标签: r

我有一个这样的数据框:

 GN  SN  
  a   b   
  a   b   
  a   c   
  d   e   
  d   f 
  d   e

我想要以下输出:
GN:a SN:2 b 1 c
 GN d SN:2 e 1 f

换句话说,我希望在S.N.列上有一种data.frame的table()。首先,我根据$ GN分割了data.frame,所以我有块。在这一点上,根据我所做的分裂,我无法对列SN上的元素进行计数。 “apply”功能是一种方法吗?如何保存属于split函数的常规输出?

提前致谢

1 个答案:

答案 0 :(得分:0)

使用您的数据:

df <- data.frame(GN = rep(c("a","b"), each = 3),
                 SN = c(rep("b", 2), "c", "e", "f", "e"))

我们可以做到:

> lapply(with(df, split(SN, GN)), table)
$a

b c e f 
2 1 0 0 

$b

b c e f 
0 0 2 1

但如果您不想要所有级别(0条目),那么我们需要删除空白级别:

> lapply(with(df, split(SN, GN)), function(x) table(droplevels(x)))
$a

b c 
2 1 

$b

e f 
2 1

将各个表写入文件

这并不完美,但至少你可以使用它

## save tables
tmp <- lapply(with(df, split(SN, GN)), function(x) table(droplevels(x)))

## function to write output to file `fname`
foo <- function(x, fname) {
    cat(paste(names(x), collapse = " "), "\n", file = fname, append = TRUE)
    cat(paste(x, collapse = " "), "\n", file = fname, append = TRUE)
    invisible()
}

fname <- "foo.txt"
file.create(fname)                # create file fname
lapply(tmp, foo, fname = fname)   # run our function to write to fname

这给出了:

R> readLines(fname)
[1] "b c " "2 1 " "e f " "2 1 "

或来自操作系统:

$ cat foo.txt
b c 
2 1 
e f 
2 1