Reputation: 1232
I have a table like below and I am trying to convert it in such a way that first column becomes the index i.e. I can use bar-plot like functions on it.
TFR_TT ML BGT
1 0 26795 1577776.4
2 2 2779 432500.0
3 6 1 187.2
To Something like below
ML BGT
0 26705 1577776.4
2 2779 432500.0
6 1 187.2
And then run the line chart so I can get 0,2,6 as Point between X axis as ML and Y Axis as BGT
Upvotes: 1
Views: 452
Reputation: 206616
To get the index, you have to set the rownames(). In the past, i've used a as.table.data.frame() helper function to just do
#sample data
dd<-structure(list(TFR_TT = c(0L, 2L, 6L), ML = c(26795L, 2779L,
1L), BGT = c(1577776.4, 432500, 187.2)), .Names = c("TFR_TT",
"ML", "BGT"), class = "data.frame", row.names = c("1", "2", "3"
))
barchart(as.table(dd, rownames=1)[,-1])
This takes care of reformatting the object and setting the names if you specify a rownames=
parameter.
I'll include the source here for completeness
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")
}
Upvotes: 2