r语言 - 将数据帧与来源相结合



我正在尝试以类似于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()将数据折叠为格式,这是我不想要的。使用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.frame 放在列表中,并将名称用作标识符。

从文档中:

提供.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
# 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

最新更新