将 table 的所有列与同一 'reference' 列进行比较,以查看它们是否与参考不同

Compare all columns of a table to the same 'reference' column to see if any of them differ from the reference

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

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
     }
 }

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

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

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