我正在尝试以与data.frame()
类似的方式合并R中的多个rbind()
,但是当创建新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 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
...我想最终得到一个如下所示的data.frame():
melt()
rbind()
将数据折叠为 long 格式,这是我不想要的。使用right
并未提供有关数据最初来自何处的任何线索。我需要做的是创建额外的列,引用数据的原始来源(例如上面示例中的left
和data.frame()
)。
我知道可以通过为每个原始rbind()
添加“眼睛”列然后使用ChartEntity
来实现这一点,但我想知道是否有更简洁的解决方案?
答案 0 :(得分:2)
您是否只想为每个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
答案 1 :(得分:1)
# 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