创建4列中的2列

时间:2013-01-18 19:08:55

标签: r dataframe

假设我有一个看起来像这样的data.frame:

structure(list(HUGO.Int1 = c("AATF", "AATF", "AATF", "ABHD16A", 
"ABHD16A", "ABHD16A"), Mut.Int1 = c(0, 0, 0, 0, 0, 0), HUGO.Int2 = c("DAPK3", 
"PAWR", "CHEK1", "RNF5", "ATP5G3", "HM13"), Mut.Int2 = c(0, 0, 
0, 0, 0, 0)), .Names = c("HUGO.Int1", "Mut.Int1", "HUGO.Int2", 
"Mut.Int2"), row.names = c(12223L, 15033L, 31655L, 11280L, 11463L, 
14106L), class = "data.frame")

我希望HUGO.Int2Mut.Int2 HUGO.Int1Mut.Int1

我试过

data.frame(rbind(c(plots$HUGO.Int1, plots$Mut.Int1), 
           c(plots$HUGO.Int2, plots$Mut.Int2)))

但是我只返回2列,Hugo.int1Mut.int1。我想知道如何正确粘贴第1和第2列下面的第3和第4列。

4 个答案:

答案 0 :(得分:2)

问题是你在那里卡住了rbind,有点随意。这是你的尝试可能应该是这样的:

dat <- structure(list(HUGO.Int1 = c("AATF", "AATF", "AATF", "ABHD16A", 
+ "ABHD16A", "ABHD16A"), Mut.Int1 = c(0, 0, 0, 0, 0, 0), HUGO.Int2 = c("DAPK3", 
+ "PAWR", "CHEK1", "RNF5", "ATP5G3", "HM13"), Mut.Int2 = c(0, 0, 
+ 0, 0, 0, 0)), .Names = c("HUGO.Int1", "Mut.Int1", "HUGO.Int2", 
+ "Mut.Int2"), row.names = c(12223L, 15033L, 31655L, 11280L, 11463L, 
+ 14106L), class = "data.frame")
> data.frame(col1 = c(dat[,1],dat[,3]),col2 = c(dat[,2],dat[,4]))
      col1 col2
1     AATF    0
2     AATF    0
3     AATF    0
4  ABHD16A    0
5  ABHD16A    0
6  ABHD16A    0
7    DAPK3    0
8     PAWR    0
9    CHEK1    0
10    RNF5    0
11  ATP5G3    0
12    HM13    0

答案 1 :(得分:2)

另一种方式:

names(x) <- chartr('12', 'XX', names(x)) # replaces 1s and 2s in names with 'X'
rbind(x[1:2], x[3:4])

答案 2 :(得分:1)

不确定这是否是您想要的但是有效:

data1 <- structure(list(HUGO.Int1 = c("AATF", "AATF", "AATF", "ABHD16A", 
"ABHD16A", "ABHD16A"), Mut.Int1 = c(0, 0, 0, 0, 0, 0), HUGO.Int2 = c("DAPK3", 
"PAWR", "CHEK1", "RNF5", "ATP5G3", "HM13"), Mut.Int2 = c(0, 0, 
0, 0, 0, 0)), .Names = c("HUGO.Int1", "Mut.Int1", "HUGO.Int2", 
"Mut.Int2"), row.names = c(12223L, 15033L, 31655L, 11280L, 11463L, 
14106L), class = "data.frame")

data2 <- cbind(data1$HUGO.Int2, data1$Mut.Int2)
data1$HUGO.Int2 <- NULL
data1$Mut.Int2 <- NULL
colnames(data2) <- colnames(data1)
data3 <- rbind(data1,data2)


> data3 
      HUGO.Int1 Mut.Int1
12223      AATF        0
15033      AATF        0
31655      AATF        0
11280   ABHD16A        0
11463   ABHD16A        0
14106   ABHD16A        0
7         DAPK3        0
8          PAWR        0
9         CHEK1        0
10         RNF5        0
11       ATP5G3        0
12         HM13        0

答案 3 :(得分:1)

df <- structure(list(HUGO.Int1 = c("AATF", "AATF", "AATF", "ABHD16A", 
"ABHD16A", "ABHD16A"), Mut.Int1 = c(0, 0, 0, 0, 0, 0), HUGO.Int2 = c("DAPK3", 
"PAWR", "CHEK1", "RNF5", "ATP5G3", "HM13"), Mut.Int2 = c(0, 0, 
0, 0, 0, 0)), .Names = c("HUGO.Int1", "Mut.Int1", "HUGO.Int2", 
"Mut.Int2"), row.names = c(12223L, 15033L, 31655L, 11280L, 11463L, 
14106L), class = "data.frame")

df2 <- df[,1:2]
df2[7:12,1:2] <- df[,3:4]