Daniel Jansen
Daniel Jansen

Reputation: 31

add column to existing column in r

How do I convert 2 columns from a data.frame onto 2 different columns? I.E:

Data
    A B C D
    1 3 5 7
    2 4 6 8

to

Data
    A B
    1 3
    2 4
    5 7
    6 8

Upvotes: 1

Views: 1958

Answers (4)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

You can use a fast version of rbind, rbindlist from data.table:

library(data.table)
rbindlist(lapply(seq(1, ncol(df), 2), function(i) df[,i:(i+1)]))

Upvotes: 3

Pierre L
Pierre L

Reputation: 28441

For scalability, a solution that will halve any even size data frame and append the rows:

half <- function(df) {m <- as.matrix(df)
dim(m) <- c(nrow(df)*2,ncol(df)/2)
nd <- as.data.frame(m)
names(nd) <- names(df[(1:dim(nd)[2])]);nd}

half(Data)
  A B
1 1 5
2 2 6
3 3 7
4 4 8

Upvotes: 2

SabDeM
SabDeM

Reputation: 7190

Here is my solution but it requires to change names of the columns.

names(dat) <- c("A", "B", "A", "B")
merge(dat[1:2], dat[3:4], all = T)
 A B
1 1 3
2 2 4
3 5 7
4 6 8

And here is another solution more easy.

dat[3:4, ] <- dat[ ,3:4]
dat <- dat[1:2]
dat
  A B
1 1 3
2 2 4
3 5 7
4 6 8

Upvotes: 2

C_Z_
C_Z_

Reputation: 7796

You can use rbind

rbind(df[,1:2], data.frame(A = df$C, B = df$D))

Upvotes: 3

Related Questions