【问题标题】:Checking multiple conditions and creating a new column according the check result in R检查多个条件并根据R中的检查结果创建一个新列
【发布时间】:2015-03-18 21:23:38
【问题描述】:

我想在我的数据框中检查 TRUE、FALSE、TRUE 和其他七种组合,它们有 87027 行和 3 列。我想为每一行写这样的结果;

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

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

【问题讨论】:

  • 那段代码伤了我的心
  • 感谢 Dason,我试图以最古老的方式解决我的问题,因为我是 R 的新用户

标签: r multiple-conditions


【解决方案1】:
# 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" 

而且运行时间非常短。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2022-08-12
    • 2022-06-14
    • 1970-01-01
    • 2021-12-22
    • 2022-08-13
    相关资源
    最近更新 更多