在其中包含.. 2d“ asis”对象的data.frames上进行rbind

时间:2018-10-22 09:47:09

标签: r dataframe rbind

给出两个尺寸相同且名称相同的1行data.frames

    dn1 <- structure(list(A = structure(list(V1 = 0, V2 = 0, V3 = 0, V4 = 0, 
        V5 = 0, V6 = 0, V7 = 0, V8 = -0.5, V9 = 0, V10 = -0.5), class = c("AsIs", 
    "data.frame"), row.names = 1L), B = structure(list(V1 = 0, V2 = 0, 
        V3 = 0, V4 = 0, V5 = 0, V6 = -0.5, V7 = 0, V8 = 0, V9 = 0, 
        V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0, V16 = 0, 
        V17 = 0, V18 = 0, V19 = 0, V20 = 0, V21 = 0, V22 = 0, V23 = 0, 
        V24 = 0, V25 = 0, V26 = 0, V27 = 0, V28 = 0, V29 = 0), class = c("AsIs", 
    "data.frame"), row.names = 1L)), class = "data.frame", row.names = c(NA, 
    -1L))

    dn2 <- structure(list(A = structure(list(V1 = 0, V2 = 0, V3 = 0, V4 = 0, 
        V5 = 0, V6 = 0, V7 = 0, V8 = 0, V9 = 0, V10 = 0), class = c("AsIs", 
    "data.frame"), row.names = 1L), B = structure(list(V1 = 0, V2 = 0, 
        V3 = 0, V4 = 0, V5 = 0, V6 = 0, V7 = 0, V8 = 0, V9 = 0, V10 = 0, 
        V11 = 0, V12 = 0, V13 = 0, V14 = -0.5, V15 = 0, V16 = 0, 
        V17 = 0, V18 = -0.5, V19 = 0, V20 = 0, V21 = 0, V22 = 0, 
        V23 = 0, V24 = 0, V25 = 0, V26 = 0, V27 = 0, V28 = 0, V29 = 0), class = c("AsIs", 
    "data.frame"), row.names = 1L)), class = "data.frame", row.names = c(NA, 
    -1L))

如果我rbind这两个,我会得到一个错误:

    > rbind.data.frame( dn1, dn2 )
    Error in `.rowNamesDF<-`(x, value = value) : 
      duplicate 'row.names' are not allowed
    In addition: Warning message:
    non-unique value when setting 'row.names': ‘1’ 
    >

我怀疑是由于它们中的“ A”和“ B”结构,我可以rbind( dn1$A, dn2$A)等,但是由于dn1dn2是有效的1行{{1 }}出于所有意图和目的,并且具有相同的名称和尺寸,我不应该data.frames来使用它们。

2 个答案:

答案 0 :(得分:0)

我不知道实际原因,但我想rbind在像您这样的复杂数据框架上不起作用。我想出一种方法来尽可能地实现您想要的。

> rbind.list <- mapply(rbind, dn1, dn2)
> dn3 <- data.frame(rbind.list)

> dn3$A

#   V1 V2 V3 V4 V5 V6 V7   V8 V9  V10
# 1  0  0  0  0  0  0  0 -0.5  0 -0.5
# 2  0  0  0  0  0  0  0  0.0  0  0.0

> dn3$B

#   V1 V2 V3 V4 V5   V6 V7 V8 V9 V10 V11 V12 V13  V14 V15 V16 V17  V18 V19 V20 V21
# 1  0  0  0  0  0 -0.5  0  0  0   0   0   0   0  0.0   0   0   0  0.0   0   0   0
# 2  0  0  0  0  0  0.0  0  0  0   0   0   0   0 -0.5   0   0   0 -0.5   0   0   0
#   V22 V23 V24 V25 V26 V27 V28 V29
# 1   0   0   0   0   0   0   0   0
# 2   0   0   0   0   0   0   0   0

mapply是等效的,但比分别使用rbind( dn1$A, dn2$A)rbind( dn1$B, dn2$B)更有效。

答案 1 :(得分:-1)

dplyr库中的

bind_rows更加强大,并提供了一些线索。

rbind_rows(dn1, dn2) Error in bind_rows_(x, .id) : Argument 1 can't be a list containing data frames

dn1是两个结构不同的数据帧的列表,而不是数据帧。对于dn2同样如此。