0

How can I efficiently bind two keyed columns into a single column of pairs that will preserve the lexicographic order of the two keys? I am interested in using 'loc' as a single (sorted) variable

dt = data.table( 
  loc.x = as.integer(c(1, 1, 3, 1, 3, 1)),
  loc.y = as.integer(c(1, 2, 1, 2, 1, 2)),
  value = letters[1:6]
)
setkey(dt, loc.x, loc.y)
Amitai
  • 871
  • 1
  • 8
  • 21
  • 2
    what is your expected output – mtoto Jan 14 '16 at 15:25
  • mtoto, is there something like Python's tuple? I don't even know how to represent a pair object in R – Amitai Jan 14 '16 at 15:32
  • I'm not sure, what are you trying to accomplish? – mtoto Jan 14 '16 at 15:52
  • I don't want to have two columns named 'loc.x' and 'loc.y'. I want to have a single column named 'loc'. Each entry in 'loc' should be a pair of integers. The table should be sorted lexicographically by this 'loc' variable. – Amitai Jan 14 '16 at 15:55
  • Why do you want them in a single column? What are you going to do next? – eddi Jan 14 '16 at 15:57
  • I need it just for readability. I use 'loc.x' and 'loc.y' dozens of times in the project. always together, never alone. Besides, I was wondering many times how to use "pair", or Python's "tuple", in R. This must be one of the most useful data structures natives (a point on geographical map, pixel location etc.) – Amitai Jan 14 '16 at 16:19
  • 3
    @Amitai there is no native tuple. There are packages that have a tuple in them, but most functions will just take two values (often in matrix form), so you'll be better off keeping them separate until you need to display them. When you do, just combine into a new character column however you like, e.g. `dt[, loc := paste(loc.x, loc.y)]` – eddi Jan 14 '16 at 16:24

1 Answers1

0

I'm not positive what you want but you could collapse them as characters and sort them which would give 1.1, 1.2, 1.3, ..., 2.1, 2.2, ...

> loc.x = as.integer(c(1, 1, 3, 1, 3, 1))
> loc.y = as.integer(c(1, 2, 1, 2, 1, 2))
> x = cbind(loc.x,loc.y)
> sort(apply(x, 1, function(a) paste0(as.character(a), collapse = ".")))
[1] "1.1" "1.2" "1.2" "1.2" "3.1" "3.1"
vincentmajor
  • 1,076
  • 12
  • 20