Skip to content

Instantly share code, notes, and snippets.

@MrFlick
Created May 9, 2014 18:38
Show Gist options
  • Save MrFlick/86d3b55093124bd53281 to your computer and use it in GitHub Desktop.
Save MrFlick/86d3b55093124bd53281 to your computer and use it in GitHub Desktop.
as.table.data.frame.R: converts a table-like data frame to a table.
as.table.data.frame<-function(x, rownames=0) {
numerics <- sapply(x,is.numeric)
chars <- which(sapply(x,function(x) is.character(x) || is.factor(x)))
names <- if(!is.null(rownames)) {
if (length(rownames)==1) {
if (rownames ==0) {
rownames(x)
} else {
as.character(x[,rownames])
}
} else {
rownames
}
} else {
if(length(chars)==1) {
as.character(x[,chars])
} else {
rownames(x)
}
}
x<-as.matrix(x[,numerics])
rownames(x)<-names
structure(x, class="table")
}
dd<-data.frame(Participant=letters[1:5],
Test1 = c(2,1,1,2,1),
Test2 = c(4,3,4,4,3),
Test3 = c(2,2,4,2,2),
Test4 = c(3,2,2,3,2),
Test5 = c(2,3,3,2,2)
)
as.table(MergedData)
as.table(MergedData, rownames=1)
as.table(MergedData, rownames=0)
as.table(MergedData, rownames=c(11:15))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment