【问题标题】:Joining rows within the same dataset in r在 r 中连接同一数据集中的行
【发布时间】: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 行 = 你将有“浮动”的扩展列数 = 这不好

标签: r dplyr left-join


【解决方案1】:

我们可以把每行的两列放在tibble中,然后是spread它和unnest:

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

如果您用stringsAsFactors = FALSE 定义df,您可以使用这一行,但要小心生成的结构:

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  

【讨论】:

    【解决方案2】:
    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")
    

    【讨论】:

      【解决方案3】:

      这是一个不雅的、骇人听闻的答案,但如果它像这样出现,您可以从结果中过滤除每 4 行中的第 2 行之外的所有内容。

      【讨论】:

      • 可以,但这远非理想的解决方案,而且可扩展性也不强。
      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 2012-07-07
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 2022-08-18
      相关资源
      最近更新 更多