将 setdiff 结果存储在数据框单元格中

Store setdiff results in dataframe cell

这是我的例子:

library(dplyr)
my_df <- data.frame( col_1 = I(list(c(1,2), 1 )), col_2 = c(1,2))
my_df <- my_df %>% rowwise(diff = setdiff(col_1, col_2))

它产生一个错误:

Error in rowwise(., diff = setdiff(col_1, col_2)) : 
  unused argument (diff = setdiff(col_1, col_2))

出了什么问题以及如何解决?有什么想法吗?

更新:糟糕,我只是忘了添加 mutate

my_df <- data.frame( col_1 = I(list(c(1,2), 1 )), col_2 = c(1,2))
my_df <- my_df %>% rowwise() %>% mutate(diff = setdiff(col_1, col_2))

一个选项是 map2 因为两列都是 list

library(dplyr)
library(purrr)
my_df %>%
     mutate(diff = map2(col_1, col_2, setdiff))

或者如果我们需要使用rowwise

my_df %>%
    rowwise %>% 
    mutate(diff = setdiff(col_1, col_2))