简体   繁体   English

将列添加到r中的现有列

[英]add column to existing column in r

How do I convert 2 columns from a data.frame onto 2 different columns? 如何将data.frame中的2列转换为2个不同的列? IE: 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: 您可以使用rbindlist的快速版本rbind和rbindlist:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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