user2520918
user2520918

Reputation: 21

How to order an object of type "structure" based on names(c)?

I have an object that looks like this:

structure(c(0, 2, 0, 3, 5, 0), .Names = c("6", "1", "3", "4", "2", "5" ))

I need the values of this object to be in the order indicated by the names, if they would be integers and not characters as they are now. The object should be (2, 5, 0, 3, 0, 0) i don't mind it to be a vector or a matrix with row names but I simply couldn't order this object. Thanks

Upvotes: 0

Views: 172

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70653

You have a named vector. Function structure is a convenient way of packing your objects for distribution. Notice that you're missing a comma before .Names.

x <- structure(c(0, 2, 0, 3, 5, 0), .Names = c("6", "1", "3", "4", "2", "5" ))
right.order <- order(as.numeric(names(x)))
x[right.order]

1 2 3 4 5 6 
2 5 0 3 0 0

Upvotes: 1

Related Questions