0

我有一个这样的数据框:

 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

换句话说,我想在 SN 列上有一个 data.frame 的 table() 首先我根据 $GN 拆分了 data.frame,所以我有块。在这一点上,我无法根据我所做的拆分计算 SN 列上的​​元素。“应用”功能是一种方法吗?以及如何保存属于拆分功能的一般输出?

提前致谢

4

1 回答 1

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 
于 2012-11-02T16:33:39.213 回答