我需要一個data.frame
對象「轉換」成純文本(如print
輸出到控制檯上。R | data.frame爲「純文本」
到目前爲止,我創建了以下功能(使用stringr
包),但我不知道是否已實施的功能或更有效的方法存在:
toString.data.frame = function(object, ...) {
maxLen = max(
stringr::str_length(apply(object, c(1,2), as.character)),
stringr::str_length(names(object))
);
# data-frame to character matrix
txt = apply(object, c(1,2), stringr::str_pad, width=maxLen+5, side="left");
# concatenate the columns
txt = apply(txt, 1, paste, collapse="");
# concatenate the rows
txt = paste(txt, collapse="\n");
# add column names
txt = paste(# concatenate header and body
paste(# concatenate all the headers
stringr::str_pad(# add 5 spaces on the left of each header
stringr::str_pad(names(object), width=maxLen, side="right") # fill each header
, width=maxLen+5, side="left")
, collapse="")
, txt
, sep="\n");
return(txt);
}
我添加一些可運行代碼以及一個輸出實例(每個輸出行由分隔「|」)
df = data.frame(hello=rnorm(1:15), world=rnorm(1:15));
cat(toString(object), "\n");
| a b |
| 0.217785930312173 1.35892062758937|
| -0.0529272009376736 -1.3537444650507|
| -0.0914533595349014 -0.283164123247757|
| 0.209099248751634 -0.994596208802379|
| 1.41207193727609 0.754568758899429|
| 0.0271570788346636 0.722728545001598|
| 1.09160395973882 -0.466194711071017|
| -0.676012596015548 0.247534965195453|
| 0.36022565974381 -0.318822054653857|
| 0.330251755314496 -0.379818935427323|
| 1.29858423625996 0.393100959746072|
| 1.79061048596737 0.124484229714237|
| -0.636849202004066 -1.48651181772674|
| 1.08795175312078 0.231693241998673|
| -0.810214549466222 -0.753200696904484|