あなたのデータで:
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 "
またはOSから:
$ cat foo.txt
b c
2 1
e f
2 1