[R] Sort problem with merge (again)
bdl at fwr.on.ca
Tue Sep 26 02:09:06 CEST 2006
# R version 2.3.1 (2006-06-01) Debian Linux "testing"
# Is the following behaviour a bug, feature or just a lack of
# understanding on my part? I see that this was discussed here
# last March with no apparent resolution.
d <- as.factor(c("1970-04-04","1970-08-11","1970-10-18"))
x <- c(9,10,11)
ch <- data.frame(Date=d,X=x)
d <- as.factor(c("1970-06-04","1970-08-11","1970-08-18"))
y <- c(109,110,111)
sp <- data.frame(Date=d,Y=y)
df <- merge(ch,sp,all=TRUE,by="Date")
# the rows with dates missing all ch vars are tacked on the end.
# the rows with dates missing all sp vars are sorted in with
# the row with a date with vars from both ch and sp
# is.ordered(df$Date) returns FALSE
# The rows of df are not sorted as they should be as sort=TRUE
# is the default. Adding sort=TRUE does nothing.
# So try this:
# dd <- df[order(df$Date),]
# But that doesn't work.
# Nor does sort(df$Date)
# But sort(as.vector(df$Date)) does work.
# As does order(as.vector(df$Date)), so this works:
dd <- df[order(as.vector(df$Date)),]
More information about the R-help