【问题标题】:Compare all columns of a table to the same 'reference' column to see if any of them differ from the reference将表的所有列与相同的“参考”列进行比较,以查看它们是否与参考不同
【发布时间】:2015-02-06 19:03:37
【问题描述】:

我对 R 比较陌生,不知道该怎么做。这是我认为类似的链接:

R - Comparing values in a column and creating a new column with the results of this comparison. Is there a better way than looping?

How can I compare a value in a column to the previous one using R?

comparing the columns and finding the values unique to a column using R

    Row     G1        M1        M2        M3            CompareColumn
    1        2         2         2         2                None
    2        1         2         2         2                G1
    3        1         2         2         2                G1
    4        1         3         3         3                G1
    5        3         2         1         3                G1, M1
    6        3         1         1         1                G1
    7        2         2         2         2                None
    8        2         2         2         2                None
    9        1         2         3         1                G1, M2
    10       2         2         3         2                M2

我想将 G1、M1 和 M2 的值与 M3 进行比较。如果其中任何一个与 M3 不同,则在 CompareColumn 中打印不同列的名称。

这里有一些伪代码可能会有所帮助:

 for each column in row 
 {
   if value in column != M3
     {
     df$CompareColumn = column.name
##when there's already a name, add ", " + column.name
     }

   else 
     {
     df$CompareColumn = None
     }
 }

【问题讨论】:

    标签: r compare multiple-columns


    【解决方案1】:

    将想法从字面上翻译成代码,这可能会有所帮助:

    a$CompareColumn <- apply(a[, 2:4] != a[, 5], 1, function(x) ifelse(any(x), paste(colnames(a)[2:4][x], collapse=', '), 'None'))
    

    不过,肯定有一些更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      相关资源
      最近更新 更多