R – Ordering Merged data frames


As a fairly new R programmer I seem to have run into a strange problem – probably my inexperience with R

After reading and merging successive files into a single data frame, I find that order does not sort the data as expected.

I have multiple references in each file but each file refers to measurement data obtained at a different time.

Here's the code

# Enter file name to Read & Save data
FileName=readline("Enter File name:\n")
# Find first occurance of file
for ( round1 in 1 : 6) {
ReadFile=paste(round1,"C_",FileName,"_Stats.csv", sep="")
if (file.exists(ReadFile))

x = data.frame(read.csv(ReadFile, header=TRUE),rnd=round1)
for ( round2 in (round1+1) : 6) {
ReadFile=paste(round2,"C_",FileName,"_Stats.csv", sep="")
if (file.exists(ReadFile)) {
y = data.frame(read.csv(ReadFile, header=TRUE),rnd = round2)
    if (round2 == (round1 +1))
ordered = order(z$lab_id)

results = z[ordered,]

res = data.frame( lab=results[,"lab_id"],bw=results[,"ZBW"],wi=results[,"ZWI"],pf_zbw=0,pf_zwi=0,r = results[,"rnd"])

# Establish no of samples recorded
nsmpls = length(res[,c("lab")])

# Evaluate Z_scores for Between Lab Results
for ( i in 1 : nsmpls) {
if (res[i,"bw"] > 3 | res[i,"bw"] < -3)
# Evaluate Z_scores for Within Lab Results
for ( i in 1 : nsmpls) {
if (res[i,"wi"] > 3 | res[i,"wi"] < -3)

dd = melt(res, id=c("lab","r"), "pf_zbw")
b = cast(dd, lab ~ r)

If anyone could see why the ordering only works for about 55 of 70 records and could steer me in the right direction I would be obliged

Thanks very much

Best Solution

Check whether z$lab_id is a factor (with is.factor(z$lab_id)).

If it is, try

z$lab_id <- as.character(z$lab_id)

if it is supposed to be a character vector; or

z$lab_id <-    as.numeric(as.character(z$lab_id))

if it is supposed to be a numeric vector.

Then order it again.

Ps. I had previously put these in the comments.

Related Question