R 根据数据帧的来源组合数据帧

R 根据数据帧的来源组合数据帧,r,dataframe,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 Colou

我正试图以类似于
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)
左眼

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()
将数据折叠为长格式,这是我不想要的。使用
rbind()
无法提供任何有关数据最初来源的线索。我需要做的是创建引用原始数据源的额外列(即上面示例中的
right
left


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

您是否只需要为每个数据帧添加一个数字标识符。您可以:

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
    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

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

从文件中:

当提供
.id
时,将创建一列新的标识符来链接 将每一行复制到其原始数据帧。标签取自
bind_rows()
的命名参数当数据帧列表为 提供的标签取自列表的名称。如果没有名字 如果找到,则使用数字序列

比如:

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

您可以从
dplyr
-
bind_行(df1,df2,.id=“id”)
Fyi使用
bind_行()
中的
.id
参数,最好生成可复制的数据,供回答者简单地复制粘贴(以便更容易地测试潜在的解决方案)。一些指导:例如,请参见下面allinr的答案,尽管它可能应该使用
set.seed