简体   繁体   中英

add column to existing column in r

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

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

您可以使用rbind

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

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

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

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)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM