在r中的同一数据集中连接行

问题描述 投票:1回答:3

我有一个如下所示的数据集:

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

有任何想法吗?提前致谢。

r dplyr left-join
3个回答
0
投票

这是一个不优雅的hack-y答案,但如果它像这样出来,你可以过滤除结果中每4行中的第2行以外的所有内容。


0
投票

希望这可以帮助!

library(dplyr)
library(splitstackshape) 

df %>%
  group_by(status) %>%
  summarise_all(funs(paste(.,collapse=","))) %>%
  cSplit(colnames(.)[-1],",")

输出是:

   status name_1 name_2 name_3 cost_1 cost_2 cost_3
1:    bar   john   matt     NA      3      4     NA
2:    foo    joe  steve   Prem      1      2      5

样本数据:

df <- structure(list(status = structure(c(2L, 2L, 1L, 1L, 2L), .Label = c("bar", 
"foo"), class = "factor"), name = structure(c(1L, 5L, 2L, 3L, 
4L), .Label = c("joe", "john", "matt", "Prem", "steve"), class = "factor"), 
    cost = c(1, 2, 3, 4, 5)), .Names = c("status", "name", "cost"
), row.names = c(NA, -5L), class = "data.frame")

0
投票

我们可以在tibble的每一行上放两列,然后spreadunnest

library(tidyverse)
df$xy <- c("x","y")
df %>%
  transmute(status,name_cost=map2(name,cost,~tibble(name=.x,cost=.y)),xy) %>%
  spread(xy,name_cost) %>%
  unnest

#   status name cost name1 cost1
# 1    bar john    3  matt     4
# 2    foo  joe    1 steve     2

如果你用df定义stringsAsFactors = FALSE你可以使用这个衬里,但要小心得到的结构:

aggregate(cbind(name,cost) ~ status,df,identity)
#   status name.1 name.2 cost.1 cost.2
# 1    bar   john   matt      3      4
# 2    foo    joe  steve      1      2  
© www.soinside.com 2019 - 2024. All rights reserved.