Virju Chaudhary
Virju Chaudhary

Reputation: 3

Append observation at end of row from another column in R

I have data with 900 rows and 400 columns. Each two column carry particular information. Let me say, there are A B C D column, I will like append C and C column just end of A and B column.

For example:


A   B   C   D   E   F  
3   4   5   6   7   8
9   10  11  12  13  14

to change to

Column 1   Column 2 
3            4 
9            10
5            6
11           12
7            8
13           14

Upvotes: 0

Views: 173

Answers (2)

Neal Fultz
Neal Fultz

Reputation: 9687

Assuming o is all numeric, convert to a matrix:

o <- read.table(text='A   B   C   D   E   F  
3   4   5   6   7   8
9   10  11  12  13  14', header=TRUE)

o <- as.matrix(o)

First, you actually have pairs of columns, so this could be thought of as a 3D array. We can reshape to 3d in-place:

dim(o) <- c(2,2,3)

So o looks like this:

> o
, , 1

     [,1] [,2]
[1,]    3    4
[2,]    9   10

, , 2   

     [,1] [,2]
[1,]    5    6
[2,]   11   12

, , 3   

     [,1] [,2]
[1,]    7    8
[2,]   13   14

Using aperm to move the indices, and dim<- to reshape, we can get pretty close:

>`dim<-`(aperm(o, c(3,1,2)), c(6,2))

     [,1] [,2]
[1,]    3    4
[2,]    5    6
[3,]    7    8
[4,]    9   10
[5,]   11   12
[6,]   13   14

If you actually want it in exactly the 2d order above you need a transpose:

> t(`dim<-`(aperm(o, c(2,1,3)), c(2,6)))
     [,1] [,2]
[1,]    3    4
[2,]    9   10
[3,]    5    6
[4,]   11   12
[5,]    7    8
[6,]   13   14

Upvotes: 0

mtoto
mtoto

Reputation: 24188

You could create the new data.frame by stacking the odd and even columns of the original df into 2 new columns.

df1 <- data.frame(Column1 = unlist(df[,c(T,F)]), 
                  Column2 = unlist(df[,c(F,T)]))
> df1
#   Column1 Column2
#A1       3       4
#A2       9      10
#C1       5       6
#C2      11      12
#E1       7       8
#E2      13      14

Upvotes: 2

Related Questions