How to order data horizontally (column-wise)?
I have data in the following manner. For each category x
taking values a, b, or c, y
is an integer.
x1 | y1 | x2 | y2 | x3 | y3 | x4 | y4 |
---|---|---|---|---|---|---|---|
b | 7 | b | 4 | c | 4 | b | 1 |
a | 5 | a | 9 | b | 1 | b | 7 |
I'd like to sort the data in ascending order column-wise (horizontally) when x = "b"
. Desired output:
x1 | y1 | x2 | y2 | x3 | y3 | x4 | y4 |
---|---|---|---|---|---|---|---|
b | 1 | b | 4 | b | 7 | c | 4 |
b | 1 | b | 7 | a | 5 | a | 9 |
I tried using a bubble sort algorithm to arrange the y
values, but unable to conditionally do it when x = "b"
. Any help is appreciated!
Answer
A little awkward, but works.
lapply(asplit(dat, 1), matrix, ncol=2, byrow=TRUE) |>
lapply(as.data.frame) |>
sapply(\(x) {
s <- split(x, x[, 1] == 'b')
s$`TRUE` <- s$`TRUE`[order(s$`TRUE`[, 2]), ]
r <- rbind(s$`TRUE`, s$`FALSE`)
asplit(r, 1) |> unlist()
}) |> t() |> as.data.frame() |> setNames(names(dat))
# x1 y1 x2 y2 x3 y3 x4 y4
# 1 b 1 b 4 b 7 c 4
# 2 b 1 b 7 a 5 a 9
Data:
dat <- yaj::read.table2('x1 y1 x2 y2 x3 y3 x4 y4
b 7 b 4 c 4 b 1
a 5 a 9 b 1 b 7')
0 Comments
If you have any doubts, Please let me know