首页 > 解决方案 > 根据多列中的最高值和另一列中的值标签分配列值

问题描述

我需要一个函数来在“ans”列中分配值,该列代表(c1l,c2l,c3l)之间的最大值 - 这些是与它们在 c1,c2,c3 中的字符值相对应的数值。对于“ans”中的第 1 行,值“B”是从“ans”中的 c2 列分配的,因为 13 是 c1l、c2l、c3l 中的最大值,而 c2l 表示 c2 中的值标签(“B”)。如果所有其他列的值都是 NA,则 col "ans" 将采用 c1l、c2l、c3l 之间的唯一值并将字符值从 c1、c2、c3 分配给 ans。所以这个函数的逻辑类似于这样:

条件 1:如果 c1l,c2l,c3l 之间的最大值则 ans = c(i) with i 在 cols c1-c3 之间

条件 2:如果 c1l,c2l,c3l 都是 NA 则 ans=c1

谢谢!

c1<-c("A","B","NA","B")
c2<-c("B","C","D","A")
c3<-c("C","A","C","C")
c1l<-c(10,12,NA,NA)
c2l<-c(13,11,NA,NA)
c3l<-c(9,10,5,NA)
ans<-c("B","A","C","B")

标签: r

解决方案


我们可以使用max.col

df <- data.frame(c1, c2, c3, c1l, c2l, c3l)
#get the value columns 
cols <- grep('c\\d+l', names(df))
#Replace NA with 0 and get the max value in each row
cols_index <- max.col(replace(df[cols], is.na(df[cols]), 0))
#If all the values are NA in a row replace it with NA
cols_index[rowSums(!is.na(df[cols]), na.rm = TRUE) == 0] <- NA
#get the corresponding label column creating a row/column matrix
df$ans <- df[-cols][cbind(1:nrow(df), cols_index)]
df$ans
#[1] "B" "B" "C" NA 

要检查 , ,之一中是否只有一个值c1,我们可以这样做c2c3

inds <- rowSums(!is.na(df[is.na(df$ans), -cols])) == 1
if(any(inds)) df$ans[inds] <- sapply(inds, function(x) 
                                na.omit(unlist(df[x, -cols])))

推荐阅读