检查多个条件并根据R中的检查结果创建新列

Checking multiple conditions and creating a new column according the check result in R

我想在我的数据框中检查 TRUE、FALSE、TRUE 和其他七个组合,其中有 87027 行和三个 columns.I 想像这样为每一行写结果;

TRUE TRUE TRUE -> abc
TRUE TRUE FALSE-> ab
TRUE FALSE TRUE->ac
FALSE TRUE TRUE->bc

和其他人...

这是一个简化的示例数据框:

 A      B      C
TRUE  FALSE  FALSE
TRUE  FALSE  FALSE
FALSE FALSE  FALSE
TRUE  FALSE  TRUE
FALSE FALSE  TRUE

为此我写了一个for循环

for (i in 1:87027) {
    if (data$A[i]=="TRUE" & data$B[i]=="TRUE" ) {
        if (data$C[i]=="TRUE") {
            data$new[i]="abc"
        }
    }
    if (data$A[i]=="TRUE" & data$B[i]=="TRUE" ) {
        if (data$C[i]=="FALSE") {
            data$new[i]="ab"
        }
    }
    if (data$A[i]=="TRUE" & data$B[i]=="FALSE" ) {
        if (data$C[i]=="TRUE") {
            data$new[i]="ac"
        }
    }
    if (data$A[i]=="TRUE" & data$B[i]=="FALSE" ) {
        if (data$C[i]=="FALSE") {
            data$new[i]="a"
        }
    }
    if (data$A[i]=="FALSE" & data$B[i]=="FALSE" ) {
        if (data$C[i]=="FALSE") {
            data$new[i]="Nothing"
        }
    }
    if (data$A[i]=="FALSE" & data$B[i]=="TRUE" ) {
        if (data$C[i]=="TRUE") {
            data$new[i]="bc"
        }
    }
    if (data$A[i]=="FALSE" & data$B[i]=="TRUE" ) {
        if (data$C[i]=="FALSE") {
            data$new[i]="b"
        }
    }
    if (data$A[i]=="FALSE" & data$B[i]=="FALSE" ) {
        if (data$C[i]=="TRUE") {
            data$new[i]="c"
        }
    }
}

运行这段代码需要几分钟时间,我想知道我怎样才能以一种复杂的方式做到这一点

# Make some sample data (you should do this next time...)
n <- 87027
col <- 3
mat <- matrix(sample(c(T,F), n*col, rep=T), n, col)

# Function that does the conversion you want
# It takes in x which is assumed to be a vector of three logical
# values
f <- function(x){
  if(all(!x)){
    return("Nothing")
  }
  out <- paste(letters[1:3][x], collapse = "")
  return(out)
}

# Use f on every row of mat
output <- apply(mat, 1, f)

产生

> head(mat)
      [,1]  [,2]  [,3]
[1,]  TRUE FALSE FALSE
[2,] FALSE  TRUE FALSE
[3,] FALSE FALSE FALSE
[4,]  TRUE FALSE  TRUE
[5,] FALSE  TRUE FALSE
[6,]  TRUE FALSE FALSE
> head(output)
[1] "a"       "b"       "Nothing" "ac"      "b"       "a" 

并且花了很少的时间 运行。