[R] Problem with names() in a plot after ordering a data.frame. Syntax or stupidity?
John Kane
jrkrideau at yahoo.ca
Sun Mar 26 20:59:01 CEST 2006
I am a complete newbie in R .
Using R 2.2.0 Windows XP
This started as a simple exercise to see if I could
produce a simple
Cleveland style dotchart with a line from the '2' axis
to the dot rather
than a continuous line as do "dotchart" and
"dotchart2". At least I could not
find that option.
I got a crude program to work but it includes
unnecessary steps.
The data in Area (below) is sorted in reverse order to
how I want it displayed
I am doing to many 'sorts' either a sort() or a rev()
to handle this problem.
When I change from sorting variables to using order()
on the data.frame I
lose my names() When I try to assign it, I get a NULL
return.
It is probably a very simple error but I cannot find
it and I am not sure if
it is syntax error, a more serious misunderstanding of
the nature of the names()
function or a confusion about how a data.frame and
order() work.
Any help gratefully received. Thanks
#-----------------------Read in
Data--------------------------------------------
Name <- c( "Nunavut", "Québec", "Northwest
Territories", "British Columbia",
"Ontario", "Alberta", "Saskatchewan",
"Manitoba", "Yukon",
"Newfoundland", "New Brunswick","Nova
Scotia", "Prince Edward Island")
Pcode <- c("NU","QC","NT","BC","ON",
"AB","SK","MB","YT","NL","NB","NS","PE")
Area <- c(1936113, 1365128, 1183085, 925186, 917741,
642317, 591670, 553556,
474391, 373872, 71450, 53338, 5660)
# ------------------------Crude working
program------------------------------
provs <- data.frame(Name, Pcode, Area)
attach(provs)
numberProvs <- length(Pcode)
# This next step reverses the order of Pcode to make
# the names match the sorted Area
names(Area) <- rev(Pcode)
Lines <- 1:numberProvs
plot(sort(Area), Lines, pch=20, col="red",
xlab = " Area", ylab= "Province or Territory",
axes=F)
axis( 2, at=Lines, labels=names(Area), las=1)
axis (1, labels= T)
xstart <- 0
xend <- Area
ystart <- rev(Lines)
yend <- rev(Lines)
arrows(xstart, ystart, xend, yend, col="red", length =
0)
# --------------End of Crude working
program-----------------------------
# --------------Revised program using order on the
data.frame-------------
provs <- data.frame(Name, Pcode, Area)
attach(provs)
numberProvs <- length(Pcode)
# Reorder the dataframe
Sizes <- provs[order(Area),]
rm (provs)
Sizes
names(Sizes$Area) <- Sizes$Pcode)
Lines <- 1:numberProvs
plot(Sizes$Area, Lines, pch=20, col="red",
xlab = " Area", ylab= "Province or Territory",
axes=F)
axis( 2, at=Lines, labels=names(Sizes$Area), las=1)
axis (1, labels= T)
xstart <- 0
xend <- Area
ystart <- rev(Lines )
yend <- rev(Lines )
arrows(xstart, ystart, xend, yend, col="red", length =
0)
# -------------End of program using order()
John Kane, Kingston ON Canada
More information about the R-help
mailing list