If your file is already a contingency table, don't use as.table()
.
df <- read.table(header=T,sep=";",text="name;7;15;25
catholic;25000;30000;15000
hinduism;5000;2000;3000")
colnames(df)[-1] <- substring(colnames(df)[-1],2)
barplot(as.matrix(df[2,2:4]), col="lightblue")
The transformation of colnames(...)
is because R doesn't like column names that start with a number, so it prepends X
. This codes just gets rid of that.
EDIT (Response to OP's comment)
If you want to convert the df
defined above to a table suitable for use with expand.table(...)
you have to set dimnames(...)
and names(dimnames(...))
as described in the documentation for expand.table(...)
.
tab <- as.matrix(df[-1])
dimnames(tab) <- list(df$name,colnames(df)[-1])
names(dimnames(tab)) <- c("name","age")
library(epitools)
x.tab <- expand.table(tab)
str(x.tab)
# 'data.frame': 80000 obs. of 2 variables:
# $ name: Factor w/ 2 levels "catholic","hinduism": 1 1 1 1 1 1 1 1 1 1 ...
# $ age : Factor w/ 3 levels "7","15","25": 1 1 1 1 1 1 1 1 1 1 ...