【发布时间】:2018-02-28 05:52:31
【问题描述】:
我有一个如下所示的数据集:
df <- data.frame(
status = c('foo','foo','bar', 'bar'),
name = c("joe", "steve", "john","matt"),
cost = c(1,2,3,4)
)
df
status name cost
foo joe 1
foo steve 2
bar john 3
bar matt 4
我想对其进行转换,以便根据状态与另一行匹配的每一行与其对应的行连接在一起。所以它应该是这样的:
status name.y cost.y name.x cost.x
foo joe 1 steve 2
bar john 3 matt 4
我正在尝试像这样使用 left_join:
df %>%
left_join(
x = ., y = ., by = 'status')
)
但是我得到的结果是这样的:
status cost.x name.x cost.y name.y
foo 1 joe 1 joe
foo 1 joe 2 steve
foo 2 steve 1 joe
foo 2 steve 2 steve
bar 3 john 3 john
bar 3 john 4 matt
bar 4 matt 3 john
bar 4 matt 4 matt
【问题讨论】:
-
如果每个 'status' 值的行数相同,例如,对于 ''foo' 你有 2 行 - 那么这个任务可以通过使用简单的“for”循环和等等但是如果你有不同的行数,例如,状态为“foo”的 2 行,状态为“bar”的 3 行 = 你将有“浮动”的扩展列数 = 这不好