r - 根据数据框的来源合并数据框

标签 r dataframe

<分区>

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

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

右眼

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() 添加一个“眼睛”列然后使用 rbind() 来实现,但是我想知道是否有更简洁的解决方案可用?

最佳答案

如果您只想为每个 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 放在一个列表中,并将名称用作标识符。

来自文档:

When .id is supplied, a new column of identifiers is created to link each row to its original data frame. The labels are taken from the named arguments to bind_rows(). When a list of data frames is supplied, the labels are taken from the names of the list. If no names are found a numeric sequence is used instead.

类似于:

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

关于r - 根据数据框的来源合并数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41245375/

相关文章:

r - 使用 qplot 仅绘制数据的一个子集

直接在 Ubuntu 14.04 中运行 JGR for R

python - Pandas:在半重叠的列上连接两个数据框

r - 使用 R 中的键值映射转换值向量(相当于 HashMap)

python - 使用 python 删除空行和空 [ ]

r - 数据框中凌乱的日期格式

r - 如何附加到 R 历史文件而不是覆盖?

r - R中的神经网络包-如何在训练收敛之前获得权重?

r - 具有相同向量的 expand_grid

python - 每个唯一列值的天数和扩展评级