【问题标题】:Comparing all elements in a cell of a row with all elements in a cell in the other row without considering the order在不考虑顺序的情况下将一行单元格中的所有元素与另一行单元格中的所有元素进行比较
【发布时间】:2019-07-01 17:03:54
【问题描述】:

我有一个包含 2 列 AB 的工作表,如图所示,其中的条目用逗号分隔 (,)。 我想在 R 中逐个单元格比较这 2 行,使其仅在以下情况下返回 1 (TRUE)

  1. 当所有条目在两行中都匹配时
  2. 比较时不考虑顺序(图片中的第 5 行)

图像的“结果”列中给出了示例预期输出。 我在 R 中使用了 match 命令,但它只为第 2 行返回 1 (True) 而不是第 5 行,它具有相同的条目但顺序不同。

有人可以建议 R 中的任何包或函数来帮助我做到这一点(最好是没有循环的解决方案),因为我想在有数千行的数据集上使用它。

【问题讨论】:

  • 请使用dput()添加您的数据。

标签: r excel comparison match rstudio


【解决方案1】:

这应该会有所帮助:

# example data
dt = data.frame(A = c("1,ab", "1,x,df"),
                B = c("2,ab", "1,df,x"),
                stringsAsFactors = F)

# vectorised function to check matches
ff = function(x,y) as.numeric(identical(sort(unlist(strsplit(x,","))), 
                                        sort(unlist(strsplit(y,",")))))
ff = Vectorize(ff)

# apply function
dt$Result = ff(dt$A, dt$B)

dt

#        A      B Result
# 1   1,ab   2,ab      0
# 2 1,x,df 1,df,x      1

如果逗号后面可能有一些空格,您可以在上面的函数中使用函数trimws,例如sort(trimws(unlist(strsplit(x,","))))

【讨论】:

    【解决方案2】:

    这是tidyverse的选项

    library(tidyverse)
    rownames_to_column(dt, 'rn') %>%
      separate_rows(A, B) %>% 
      group_by(rn) %>% 
      summarise(Result = as.integer(all(sort(A) == sort(B)))) %>% 
      select(Result) %>% 
      bind_cols(dt, .)
    

    数据

    dt <- structure(list(A = c("1,ab", "1,x,df"), B = c("2,ab", "1,df,x"
    )), class = "data.frame", row.names = c(NA, -2L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2017-05-31
      • 1970-01-01
      相关资源
      最近更新 更多