【问题标题】:Combine dataframes with reference to where they came from [duplicate]结合数据框参考它们的来源[重复]
【发布时间】:2016-12-20 15:05:16
【问题描述】:

我正在尝试以与rbind() 类似的方式在 R 中组合多个 data.frame()s,但是当创建新的 data.frame() 时,我想知道原始 data.frame()s 中的哪一个数据来自。

例如,如果我有以下数据:

右眼

Vision    Colour    Prescription
  0.30    blue             -1.00
 -0.10    blue             +1.50
 (etc)    (etc)             (etc)

左眼

Vision    Colour    Prescription
  0.00    blue             +1.00
  0.10    brown            -2.50
 (etc)    (etc)             (etc)

...我想最终得到一个如下所示的 data.frame():

Vision    Colour    Prescription      Eye
  0.30    blue             -1.00      Right
 -0.10    blue             +1.50      Right
  0.00    blue             +1.00      Left
  0.10    brown            -2.50      Left

melt() 将数据折叠为 long 格式,这是我不想要的。使用rbind() 并不能提供关于数据最初来自何处的任何线索。我需要做的是创建引用原始数据源的额外列(即上面示例中的rightleft)。

我知道这可以通过在每个原始 data.frame()s 中添加一个“眼睛”列然后使用 rbind() 来实现,但我想知道是否有更简洁的解决方案可用?

【问题讨论】:

  • 您可以在bind_rows() 中使用.id 参数,来自dplyr - bind_rows(df1, df2, .id = "id")
  • 仅供参考,最好制作可重复的数据,以便回答者可以简单地复制粘贴(以便更轻松地测试潜在的解决方案)。一些指导:stackoverflow.com/questions/5963269/… 例如,请参阅下面的 allinr 的答案,尽管它可能应该使用 set.seed

标签: r dataframe


【解决方案1】:

如果您只是想要每个 data.frame 的数字标识符,您可以这样做:

library(dplyr)
bind_rows(Right, Left, .id = "Eye")

这给出了:

 Eye Vision Colour Prescription
1   1    0.3   blue         -1.0
2   1   -0.1   blue          1.5
3   2    0.0   blue          1.0
4   2    0.1  brown         -2.5

您还可以将 data.frames 放在一个列表中,并使用名称作为标识符。

来自文档:

当提供.id 时,会创建一个新的标识符列来链接 每一行到它的原始数据框。标签取自 bind_rows() 的命名参数。 当数据框列表是 提供时,标签取自列表的名称。如果没有名字 发现使用数字序列代替。

类似:

dat <- c("Right", "Left")
lst <- mget(dat)
bind_rows(lst, .id = "Eye")

这给出了:

    Eye Vision Colour Prescription
1 Right    0.3   blue         -1.0
2 Right   -0.1   blue          1.5
3  Left    0.0   blue          1.0
4  Left    0.1  brown         -2.5

【讨论】:

    【解决方案2】:
    # Generate random data
    set.seed(42)
    Right = setNames(object = data.frame(replicate(3,sample(0:1,3,rep=TRUE))),
                     nm = c('Vision', 'Color', 'Prescription'))
    Left = setNames(object = data.frame(replicate(3,sample(0:1,3,rep=TRUE))),
                    nm = c('Vision', 'Color', 'Prescription'))
    
    rbind(cbind(Right, Eye = "Right"), cbind(Left, Eye = "Left"))
    #  Vision Color Prescription   Eye
    #1      1     1            1 Right
    #2      1     1            0 Right
    #3      0     1            1 Right
    #4      1     1            1  Left
    #5      0     0            1  Left
    #6      1     0            0  Left
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2018-10-01
      相关资源
      最近更新 更多