R 基于优先级列表在数据帧中选择值

R 基于优先级列表在数据帧中选择值,r,R,我是R的新手,所以我仍然在思考它的工作方式。我的问题如下,我有一个数据框和列的优先级列表(pl),我需要: 要从pl中的列中查找每行的最大值,并使用此值创建一个新列(df$max) 使用优先级列表,从优先级值中减去此最大值,忽略NAs并返回绝对差值 举个例子可能更好: 我的优先事项是 pl <- c("E","D","A","B") 因此,对于第一行,最大值来自列A(15),优先级值来自列D(9),因为E是NA。我想要的答案应该是这样的 A B C D E F

我是R的新手,所以我仍然在思考它的工作方式。我的问题如下,我有一个数据框和列的优先级列表(
pl
),我需要:

  • 要从
    pl
    中的列中查找每行的最大值,并使用此值创建一个新列(
    df$max
  • 使用优先级列表,从优先级值中减去此最大值,忽略NAs并返回绝对差值
  • 举个例子可能更好: 我的优先事项是

    pl <- c("E","D","A","B")
    
    因此,对于第一行,最大值来自列A(15),优先级值来自列D(9),因为E是NA。我想要的答案应该是这样的

        A   B   C   D   E   F   G   MAX MAX-PR
    1   15  5   20  9   NA  6   1   15  6
    2   3   2   NA  5   1   3   2   5   4
    3   NA  NA  3   NA  NA  NA  NA  NA  NA
    4   0   1   0   7   8   NA  6   8   0
    5   1   2   3   NA  NA  1   6   2   1
    
    这个怎么样

    df$MAX <- apply(df[,pl], 1, max, na.rm = T)
    df$MAX_PR <- df$MAX - apply(df[,pl], 1, function(x) x[!is.na(x)][1])
    df$MAX[is.infinite(df$MAX)] <- NA
    > df
    
    #    A  B  C  D  E  F  G MAX MAX_PR
    # 1 15  5 20  9 NA  6  1  15      6
    # 2  3  2 NA  5  1  3  2   5      4
    # 3 NA NA  3 NA NA NA NA  NA     NA
    # 4  0  1  0  7  8 NA  6   8      0
    # 5  1  2  3 NA NA  1  6   2      1
    
    df$MAX示例:

    df <- data.frame(A=c(1,NA,2,5,3,1),B=c(3,5,NA,6,NA,10),C=c(NA,3,4,5,1,4))
    pl <- c("B","A","C")
    #now we find the maximum per row, ignoring NAs
    max.per.row <- apply(df,1,max,na.rm=T)
    #and the first element according to the priority list, ignoring NAs
    #(there may be a more efficient way to do this)
    first.per.row <- apply(df[,pl],1, function(x) as.vector(na.omit(x))[1])
    #and finally compute the difference
    max.less.first.per.row <- max.per.row - first.per.row
    

    df这里是一个简单的版本。首先,我只取pl列,对于每一行,我去掉na,然后计算最大值

     df <- dat[,pl]
     cbind(dat, t(apply(df, 1, function(x) {
                          x <- na.omit(x)
                          c(max(x),max(x)-x[1])
                        }
                    )
                  )
           )
    
    
       A  B  C  D  E  F  G    1  2
    1 15  5 20  9 NA  6  1   15  6
    2  3  2 NA  5  1  3  2    5  4
    3 NA NA  3 NA NA NA NA -Inf NA
    4  0  1  0  7  8 NA  6    8  0
    5  1  2  3 NA NA  1  6    2  1
    
    df
    
     df <- dat[,pl]
     cbind(dat, t(apply(df, 1, function(x) {
                          x <- na.omit(x)
                          c(max(x),max(x)-x[1])
                        }
                    )
                  )
           )
    
    
       A  B  C  D  E  F  G    1  2
    1 15  5 20  9 NA  6  1   15  6
    2  3  2 NA  5  1  3  2    5  4
    3 NA NA  3 NA NA NA NA -Inf NA
    4  0  1  0  7  8 NA  6    8  0
    5  1  2  3 NA NA  1  6    2  1