Reputation: 722
I'm a newbie in R and I'm trying to debug a special case in my code.
In the following lines what I'm doing is getting a vector x
sorted, based a column that surely exists. Naturally, I would expect sorted.data
to be the same and in most cases it is.
print (paste("x=",typeof(x)))
print (x)
sorted.data <- x[order(x[[max.column]]), ]
print (paste("type of sorted=", typeof(sorted.data)))
print (sorted.data)
In most cases the output of the above code is:
[1] "x= list"
V1 V5
8 10 0
16 7 0
18 7 0
20 1 96
24 9 0
[1] "type of sorted= list"
V1 V5
8 10 0
16 7 0
18 7 0
24 9 0
31 5 0
But at some point, the output is:
[1] "x= list" # Expected. a vector with 1 column
V1
8 10
16 7
18 7
24 9
26 10
[1] "type of sorted= integer" # This shouldn't happen
[1] 0 0 0 1 1 1 1 2 2 3 3 4 4 4
What could be going wrong? Why the return value changes?
Upvotes: 1
Views: 77
Reputation: 160607
First, your data looks very much like a data.frame
, which is very much like a list
. If it were truly not a data.frame
, then your comma-indexing (x[order(x[[max.column]]), ]
) should not work, so I'm assuming it's a data.frame
.
One thing I find occasionally frustrating with data.frame
indexing (and array
s, too), the default behavior is that "the result is coerced to the lowest possible dimension" (extracted from help("[")
). This means that when the indexing results in only one column (or row), it is returned as a vector. To preempt this, add ,drop=FALSE
to your indexing:
x[order(x[[max.column]]),,drop=FALSE]
(Thanks to Rui Barradas for correcting my errant comment above.)
Upvotes: 2