【问题标题】:Undirected combinations of actors in the same movie同一部电影中演员的无向组合
【发布时间】:2017-11-07 02:05:17
【问题描述】:

我不确定如何描述我正在尝试执行的操作。我有一个包含两列(电影和演员)的数据框。我想根据他们在一起的电影创建一个独特的 2 演员组合列表。下面是创建我拥有的数据框示例的代码,以及另一个我想要的结果的数据框。


start_data <- tibble::tribble(
  ~movie, ~actor,
  "titanic", "john",
  "star wars", "john",
  "baby driver", "john",
  "shawshank", "billy",
  "titanic", "billy",
  "star wars", "sarah",
  "titanic", "sarah"
)

end_data <- tibble::tribble(
  ~movie, ~actor1, ~actor2,
  "titanic", "john", "billy",
  "titanic", "john", "sarah",
  "titanic", "billy", "sarah",
  "star wars", "john", "sarah"
)

感谢任何帮助,谢谢!短的话加分++

【问题讨论】:

    标签: r dataframe tidyverse purrr tibble


    【解决方案1】:

    您可以使用combn(..., 2) 查找两个actor 组合,可以将其转换为两列tibble 并使用summarize 存储在列表列中;要获取平面数据框,请使用unnest

    library(tidyverse)
    
    start_data %>% 
        group_by(movie) %>% 
        summarise(acts = list(
            if(length(actor) > 1) set_names(as.tibble(t(combn(actor, 2))), c('actor1', 'actor2')) 
            else tibble()
        )) %>% 
        unnest()
    
    # A tibble: 4 x 3
    #      movie actor1 actor2
    #      <chr>  <chr>  <chr>
    #1 star wars   john  sarah
    #2   titanic   john  billy
    #3   titanic   john  sarah
    #4   titanic  billy  sarah
    

    【讨论】:

    • 这正是我所需要的。我所做的唯一补充是添加filter(actor1 != actor2) 以删除一些案例。不过,这可能是我的数据有问题。
    • 很可能你在每部电影中都有重复的演员;您可以像以前一样应用过滤器,也可以从 combn(unique(actor), 2) 开始删除重复项。
    【解决方案2】:
    library(tidyverse)
    library(stringr)
    
    inner_join(start_data, start_data, by = "movie") %>% 
      filter(actor.x != actor.y) %>% 
      rowwise() %>% 
      mutate(combo = str_c(min(actor.x, actor.y), "_", max(actor.x, actor.y))) %>% 
      ungroup() %>%
      select(movie, combo) %>% 
      distinct %>% 
      separate(combo, c("actor1", "actor2"))
    

    【讨论】:

    • 这似乎和其他海报一样有效。我的错误是没有提供正确的样本演员数据。格式应为Lastname Firstname。需要一些小技巧才能使您的方法起作用。您的方法的另一个问题是您没有提到 str_c 来自 stringr 包。不过不难找。感谢您的努力。
    • 如果你不想使用 stringr,只需将 str_c 更改为 paste0
    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2017-04-18
    相关资源
    最近更新 更多