1

I have a huge data frame with 200 columns, something like this

A  1  E  5  I 9   ...
B  2  F  6  J 10  ...
C  3  G  7  K 10  ...
D  4  H  8  L 12  ...

what would be the best way to reorgainse 200 columns into two columns, so that:

A  1
B  2
C  3
D  4
E  5
F  6
G  7
H  8
I  9

I'm new to R. There must be a very easy way to do this, but I can't really find it. Tidyr doesn't seem to have a function for this.

AndrasG
  • 29
  • 2
  • 1
    merge every alternate columns into one? – Ronak Shah Apr 10 '18 at 09:26
  • Related post: https://stackoverflow.com/questions/24440258/selecting-multiple-odd-or-even-columns-rows-for-dataframe – zx8754 Apr 10 '18 at 09:41
  • Very similar question asked 15 hours ago: https://stackoverflow.com/questions/49739966/making-4-columns-into-1-column-in-r#comment86494704_49739966 – DJack Apr 10 '18 at 10:07

2 Answers2

3

Try this:

data.frame(col1 = unlist(df1[, c(TRUE, FALSE)]),
           col2 = unlist(df1[, c(FALSE, TRUE)]))

Probably this is a duplicate, can't find the target post...

zx8754
  • 52,746
  • 12
  • 114
  • 209
0

Read your reproducible example data:

df <- read.table(text = "A  1  E  5  I 9   ...
B  2  F  6  J 10  ...
C  3  G  7  K 10  ...
D  4  H  8  L 12  ...")

Remove the useless column

df$V7 <- NULL

Create the output by alternatively selecting column and merge them into vectors

result <- data.frame(V1 = as.vector(unlist(df[ , seq(1, dim(df)[2] -1, 2)])),
                     V2 = as.vector(unlist(df[ , seq(2, dim(df)[2], 2)])))

Print the solution:

print(result)
   V1 V2
1   A  1
2   B  2
3   C  3
4   D  4
5   E  5
6   F  6
7   G  7
8   H  8
9   I  9
10  J 10
11  K 10
12  L 12
Seymour
  • 3,104
  • 2
  • 22
  • 46