Pastebin
API
tools
faq
paste
Login
Sign up
Please fix the following errors:
New Paste
Syntax Highlighting
library(magrittr) library(stringr) # Función utilizada en Rkward para unir tablas. bind.tables <- function (...) { if (is.list(..1)) tables <- ..1 else tables <- list(...) output <- unlist(tables) dim (output) <- c(dim(tables[[1]]), length(tables)) dimnames(output) <- c (dimnames(tables[[1]]), list("statistic"=names(tables))) output } crosstable <- function(..., data=parent.frame(), row.vars = NULL, col.vars = NULL, stats = "freq", col.total = FALSE, row.total = FALSE, stats.on.cols = TRUE, digits = 2) { # This function will use table or xtabs to make an R table # can recive as arguments a couple of vectors or an already made table if (is.table(..1)) table1 <- ..1 else if (class(..1)=="formula") table1 <- xtabs(..1, data=data) else table1 <- table(...) # We should build the arguments col.vars or row.vars if not defined if(xor(is.null(col.vars), is.null(row.vars))) { if (is.null(row.vars)) { if (is.character(col.vars)) col.vars <- which(names(dimnames(table1)) %in% col.vars) row.vars <- 1:length(dim(table1)) row.vars <- row.vars[-col.vars] } else if (is.null(col.vars)) { if (is.character(row.vars)) row.vars <- which(names(dimnames(table1)) %in% row.vars) col.vars <- 1:length(dim(table1)) col.vars <- col.vars[-row.vars] } } else if(is.null(col.vars) & is.null(row.vars)) { col.vars <- length(dim(table1)) row.vars <- 1:(length(dim(table1))-1) } # The table to print will be a list of tables made with prop.table # the main table is frequency other tables are percentajes tablePrint <- lapply(stats, function(x) { if (x == "count") table1 else if (x == "total") prop.table(table1)*100 else if (x == "row") prop.table(table1, col.vars)*100 else if (x == "column") prop.table(table1, row.vars)*100 }) # This will define the names of the stats columns f <- stats %in% c("column","row","total") tableNames <- stats tableNames[f] <- paste("% of", tableNames[f]) names(tablePrint) <- tableNames tablePrint <- bind.tables(tablePrint) # The table is the main table to perform chisq. # The tablePrint is an attribute only to show. structure(table1, tablePrint = tablePrint, arguments = list(row.vars = row.vars, col.vars = col.vars, stats = stats, stats.on.cols = stats.on.cols, digits = digits), class="crosstable") } print.crosstable <- function(x) { invisible(x) #-------------------# # GENERAL VARIABLES # #-------------------# tablePrint <- attr(x, "tablePrint") arguments <- attr(x, "arguments") tableDimNames <- dimnames(tablePrint) tablePrint.names <- names(dimnames(tablePrint)) if(arguments$stats.on.cols) { col.vars <- c(arguments$col.vars, (length(dim(x))+1):length(dim(tablePrint))) row.vars <- arguments$row.vars }else{ col.vars <- arguments$col.vars row.vars <- c(arguments$row.vars, (length(dim(x))+1):length(dim(tablePrint))) } row.names <- tablePrint.names[row.vars] row.dim <- dim(tablePrint)[row.vars] col.names <- tablePrint.names[col.vars] col.dim <- dim(tablePrint)[col.vars] #-------------------------# # MAKE THE TABLE TO PRINT # #-------------------------# dimTable <- dim(tablePrint) # Index of original table to make s <- sapply(1:prod(dimTable[(length(dimTable)-1):length(dimTable)]),rep,prod(dimTable[-((length(dimTable)-1):length(dimTable))])) dim(s) <- dimTable s <- apply(s, col.vars[length(col.vars)], c) s <- sort(s, index.return=TRUE)$ix tablePrint %<>% round(arguments$digits) %>% apply(col.vars[length(col.vars)], format) #Now we sort the table using the s index tablePrint <- as.vector(tablePrint)[s] dim(tablePrint) <- dimTable f <- arguments$stats %in% c("column","row","total") tableFormat <- rep(" ", length(arguments$stats)) tableFormat[f] <- "%" # The Sweep function should add % to the cells "%p%" <- function(x,y) paste0(x,y) tablePrint <- sweep(tablePrint, length(dimTable), tableFormat, "%p%") dim(tablePrint) <- dimTable #colHeaders colHeaders <- tableDimNames[col.vars] # Table Width for columns based on the length of var labels tableWidth <- 0 for (i in length(colHeaders):1) { # Ajustment of the column width by the variable label if (nchar(names(colHeaders)[i]) > sum(nchar(colHeaders[[i]]))) { dif <- nchar(names(colHeaders)[i]) - sum(nchar(colHeaders[[i]])) extraChar <- round(dif*(nchar(colHeaders[[i]])/sum(nchar(colHeaders[[i]])))) if (sum(extraChar) < dif) extraChar <- extraChar + ceiling((dif-sum(extraChar))*(nchar(colHeaders[[i]])/sum(nchar(colHeaders[[i]])))) colWidth <- nchar(colHeaders[[i]]) + extraChar } else { colWidth <- nchar(colHeaders[[i]]) } # Ajustment of the lower level vars by the upper level vars if(sum(colWidth) > sum(tableWidth) & sum(tableWidth) > 0) { sapply(1:length(colWidth), function(x) { if(colWidth[x] > sum(tableWidth)) { dif <- colWidth[x] - sum(tableWidth) extraChar <- round(dif*(tableWidth/sum(tableWidth))) if (sum(extraChar) < dif) extraChar <- extraChar + ceiling((dif-sum(extraChar))*(tableWidth/sum(tableWidth))) tableWidth + extraChar } else { tableWidth } } ) -> tableWidth } else if (sum(tableWidth) == 0) { tableWidth <- colWidth } else { tableWidth <- rep(tableWidth, length(colWidth)) } } # Turn table in to ftable and format it to be printed tablePrint <- ftable(tablePrint, col.vars = col.vars) tableWidth <- pmax(tableWidth, nchar(apply(tablePrint,2,max))) tablePrint <- mapply(function(x,y) format(tablePrint[,x], justify ="right", width=y), 1:prod(col.dim), tableWidth) dimnames(tablePrint) <- NULL # A matrix with row headers. mapply( function(x) { rvalue <- character(0) for (i in tableDimNames[[row.names[x]]]) { rvalue <- c(rvalue,i,rep("", prod(c(row.dim,1)[(x+1):(length(row.dim)+1)])-1)) } rep(rvalue, prod(row.dim[1:x])/row.dim[x]) } , 1:length(row.dim) ) -> rowHeaders for(i in 1:ncol(rowHeaders)) rowHeaders[,i] <- format(rowHeaders[,i], width=nchar(row.names)[i]) dim(rowHeaders) <- c(prod(row.dim),length(row.dim)) rowHeaders.nchar <- nchar(rowHeaders[1,]) # Start of the table cat("|", strrep("-", sum(rowHeaders.nchar+1,tableWidth+1)-1), "|\n", sep="") #Print the table col headers colHeaders <- tableDimNames[col.vars] for (i in 1:length(col.dim)) { iColRep <- prod(c(1,col.dim)[1:i]) iColDim <- iColRep*length(colHeaders[[i]]) sapply( 1:iColRep, function(x) sum(tableWidth[1:(length(tableWidth)/iColRep)+(length(tableWidth)/iColRep)*(x-1)]) ) -> iColWidthLab sapply( 1:iColDim, function(x) sum(tableWidth[1:(length(tableWidth)/iColDim)+(length(tableWidth)/iColDim)*(x-1)]) ) -> iColWidth nSep <- prod(c(col.dim,1)[(i+1):(length(col.dim)+1)]) cat("|", paste0(strrep(" ", c(rowHeaders.nchar)), "|"), sep="") cat(paste0(stringr::str_pad(rep(names(colHeaders)[i],iColRep),iColWidthLab+nSep*col.dim[i]-1, "both"), "|"), "\n", sep="") cat("|", paste0(strrep(" ", c(rowHeaders.nchar)), "|"), strrep("-", sum(tableWidth+1)-1), "|\n", sep="") if (i==length(col.dim)) { cat("|", paste0(stringr::str_pad(row.names,rowHeaders.nchar,"both", " "),"|"), sep="") } else { cat("|", paste0(strrep(" ", c(rowHeaders.nchar)), "|"), sep="") } cat(paste0(stringr::str_pad(rep(colHeaders[[i]],iColRep),iColWidth+nSep-1, "both"), "|"), "\n", sep="") if (i<length(col.dim)) cat("|", paste0(strrep(" ", c(rowHeaders.nchar)), "|"), strrep("-", sum(tableWidth+1)-1), "|\n", sep="") } # Printing the final table cat("|", paste0(strrep("-", c(rowHeaders.nchar,tableWidth)), "|"),"\n", sep="") for (i in 1:prod(row.dim)) { cat("|", paste0(rowHeaders[i,],"|"), sep="") cat(paste0(tablePrint[i,], "|"), sep="") cat("\n") } # Close of the table cat("|", strrep("-", sum(rowHeaders.nchar+1,tableWidth+1)-1), "|\n", sep="") } ## Prueba con dos variables generadas aleatoriamente gender <- sample(c(1,2), 131, replace=TRUE) %>% factor(levels=c(1,2), labels=c("Man", "Woman")) strata <- sample(c(1,2,3), 131, replace=TRUE) %>% factor(levels=c(1,2,3), labels=c("Low", "Middle", "High")) party <- sample(c(1,2), 131, replace=TRUE) %>% factor(levels=c(1,2), labels=c("Right", "Left")) crosstable(gender, strata, party, stats=c("count", "column", "row"))
Optional Paste Settings
Category:
None
Cryptocurrency
Cybersecurity
Fixit
Food
Gaming
Haiku
Help
History
Housing
Jokes
Legal
Money
Movies
Music
Pets
Photo
Science
Software
Source Code
Spirit
Sports
Travel
TV
Writing
Tags:
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
JSON
Java
JavaScript
Lua
Markdown (PRO members only)
Objective C
PHP
Perl
Python
Ruby
Swift
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
AIMMS
ALGOL 68
APT Sources
ARM
ASM (NASM)
ASP
ActionScript
ActionScript 3
Ada
Apache Log
AppleScript
Arduino
Asymptote
AutoIt
Autohotkey
Avisynth
Awk
BASCOM AVR
BNF
BOO
Bash
Basic4GL
Batch
BibTeX
Blitz Basic
Blitz3D
BlitzMax
BrainFuck
C
C (WinAPI)
C Intermediate Language
C for Macs
C#
C++
C++ (WinAPI)
C++ (with Qt extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
CMake
COBOL
CSS
Ceylon
ChaiScript
Chapel
Clojure
Clone C
Clone C++
CoffeeScript
ColdFusion
Cuesheet
D
DCL
DCPU-16
DCS
DIV
DOT
Dart
Delphi
Delphi Prism (Oxygene)
Diff
E
ECMAScript
EPC
Easytrieve
Eiffel
Email
Erlang
Euphoria
F#
FO Language
Falcon
Filemaker
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
GDB
GDScript
Game Maker
Genero
Genie
GetText
Go
Godot GLSL
Groovy
GwBasic
HQ9 Plus
HTML
HTML 5
Haskell
Haxe
HicEst
IDL
INI file
INTERCAL
IO
ISPF Panel Definition
Icon
Inno Script
J
JCL
JSON
Java
Java 5
JavaScript
Julia
KSP (Kontakt Script)
KiXtart
Kotlin
LDIF
LLVM
LOL Code
LScript
Latex
Liberty BASIC
Linden Scripting
Lisp
Loco Basic
Logtalk
Lotus Formulas
Lotus Script
Lua
M68000 Assembler
MIX Assembler
MK-61/52
MPASM
MXML
MagikSF
Make
MapBasic
Markdown (PRO members only)
MatLab
Mercury
MetaPost
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MySQL
Nagios
NetRexx
Nginx
Nim
NullSoft Installer
OCaml
OCaml Brief
Oberon 2
Objeck Programming Langua
Objective C
Octave
Open Object Rexx
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
PARI/GP
PCRE
PHP
PHP Brief
PL/I
PL/SQL
POV-Ray
ParaSail
Pascal
Pawn
Per
Perl
Perl 6
Phix
Pic 16
Pike
Pixel Bender
PostScript
PostgreSQL
PowerBuilder
PowerShell
ProFTPd
Progress
Prolog
Properties
ProvideX
Puppet
PureBasic
PyCon
Python
Python for S60
QBasic
QML
R
RBScript
REBOL
REG
RPM Spec
Racket
Rails
Rexx
Robots
Roff Manpage
Ruby
Ruby Gnuplot
Rust
SAS
SCL
SPARK
SPARQL
SQF
SQL
SSH Config
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
StandardML
StoneScript
SuperCollider
Swift
SystemVerilog
T-SQL
TCL
TeXgraph
Tera Term
TypeScript
TypoScript
UPC
Unicon
UnrealScript
Urbi
VB.NET
VBScript
VHDL
VIM
Vala
Vedit
VeriLog
Visual Pro Log
VisualBasic
VisualFoxPro
WHOIS
WhiteSpace
Winbatch
XBasic
XML
XPP
Xojo
Xorg Config
YAML
YARA
Z80 Assembler
ZXBasic
autoconf
jQuery
mIRC
newLISP
q/kdb+
thinBasic
Paste Expiration:
Never
Burn after read
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Exposure:
Public
Unlisted
Private
Folder:
(members only)
Password
NEW
Enabled
Disabled
Burn after read
NEW
Paste Name / Title:
Create New Paste
Hello
Guest
Sign Up
or
Login
Sign in with Facebook
Sign in with Twitter
Sign in with Google
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Public Pastes
anydesk forensics
1 hour ago | 0.80 KB
OoTMM rando seed 7/28
5 hours ago | 93.67 KB
Untitled
6 hours ago | 5.87 KB
EARNING-BTC ENGINE
CSS | 6 hours ago | 0.38 KB
Secret Guide
6 hours ago | 0.39 KB
Step 7 Enumeration
12 hours ago | 19.79 KB
Disable Drag and Drop Image Improved Plugin i...
PHP | 1 day ago | 1.31 KB
z66is_archive.zip.txt
1 day ago | 1.53 KB
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the
Cookies Policy
.
OK, I Understand
Not a member of Pastebin yet?
Sign Up
, it unlocks many cool features!