データフレーム・行列をタブ区切りで整形して書き出す Last modified: Mar 20, 2006
目的
R のデータフレームまたは行列を,タブ区切りで整形して書き出す関数。
使用法
print.fixed(x, format=NULL)
print(x, format=NULL) # x のクラスが "fixed" のときにはこのように省略することも可
引数
x, # データフレームまたは行列。クラスとして "fixed" を与えるとよいこともある
format=NULL # 表示書式。format="f5 i s" など
ソース
インストールは,以下の 1 行をコピーし,R コンソールにペーストする
source("http://aoki2.si.gunma-u.ac.jp/R/src/print.fixed.R", encoding="euc-jp")
# データフレーム・行列をタブ区切りで整形して書き出す
print.fixed <- function(x, # データフレームまたは行列。クラスとして "fixed" を与えるとよいこともある
format=NULL) # 表示書式。format="f5 2i s" など
{
if (!is.matrix(x)) { # 行列でないなら,
x <- as.matrix(x) # 行列にしてしまう
}
nr <- nrow(x) # 行数
nc <- ncol(x) # 列数
if (is.null(format)) { # format が NULL なら,
format <- rep("%20s", nc) # 適当に作る
}
else { # format が与えられているなら,
format <- unlist(strsplit(format, "[ ,]")) # sprintf で使える,正式な format に変換する
format <- unlist(sapply(format, function(str) { # Rf3 のような形式(R 繰り返し)に対応
rep <- sub("[a-z]+[0-9]*", "", str)
if (rep == "") {
rep <- "1"
}
rep <- as.integer(rep)
fmt <- sub("^[0-9]*", "", str)
return(rep(fmt, rep))
}))
if (nc != length(format)) { # 書式は十分か?
stop("insufficient format")
}
format <- sapply(1:nc, function(i) {
fmt <- format[i]
ch <- substring(fmt, 1, 1)
if (ch == "f") {
format[i] <- paste("%.", substring(fmt, 2), "f", sep="")
}
else {
format[i] <- paste("%", ch, sep="")
}
})
}
for (i in 1:nr) {
for (j in 1:nc) {
number <- suppressWarnings(as.numeric(x[i,j]))
if (is.na(number)) {
if (x[i,j] == "NA") x[i,j] = ""
cat(sprintf("%s", x[i,j]), if (j==nc) "\n" else "\t", sep="")
}
else {
cat(sprintf(format[j], number), if (j==nc) "\n" else "\t", sep="")
}
}
}
}
使用例
> y <- matrix(rnorm(15),3)
> print.fixed(y,format="f1,f2,f3,f4,f5")
-1.0 0.91 0.637 -0.1823 1.08874
-1.8 2.52 -1.169 0.0323 0.56543
-1.3 1.59 0.174 -1.1349 2.02057
> class(y) <- "fixed"
> print(y,format="f1,f2,f3,f4,f5")
# fixed クラスにすると,print 関数は print.fixed を呼ぶ。
-1.0 0.91 0.637 -0.1823 1.08874
-1.8 2.52 -1.169 0.0323 0.56543
-1.3 1.59 0.174 -1.1349 2.02057
> y
# 単に fixed クラスのオブジェクトを書くと,print.fixed をデフォルトパラメータで呼び出すのと同じ
-1.04918796502011 0.912869391443626 0.637270462812026 -0.182304192056849 1.08874402303749
-1.75036703633735 2.51551381789059 -1.16895259373021 0.0323167907684786 0.565433918647744
-1.31616310969960 1.58936914358683 0.173722088243833 -1.13491087137664 2.02057498588021
# data.frame の場合には,単に "fixed" クラスにするのではなく
# class(object) <- c("fixed", "data.frame") とすること
> x <- 1:5
> y <- rnorm(5)
> z <- month.name[1:5]
> df <- data.frame(x=x, y=y, z=z)
> class(df) <- "fixed"
> df
以下にエラーas.double.default(x[i, j]) : (list)オブジェクトは 'double' に変換できません
> class(df) <- c("fixed", "data.frame")
> df
1 -0.329225 January
2 -0.5205364 February
3 0.6276814 March
4 -2.2003986 April
5 0.4810544 May
> print(df)
1 -0.329225 January
2 -0.5205364 February
3 0.6276814 March
4 -2.2003986 April
5 0.4810544 May
> print(df, format="i2 f3 s3")
1 -0.329 January
2 -0.521 February
3 0.628 March
4 -2.200 April
5 0.481 May
直前のページへ戻る
E-mail to Shigenobu AOKI