2015-03-18 58 views
1

中的檢查結果檢查多個條件並創建一個新列我想在我的數據框中檢查TRUE,FALSE,TRUE和其他七個組合,其中有87027行和三列。我想爲每個這樣的排;根據R

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

運行此代碼取幾分鐘,我想知道我怎麼能做到這一點的一種複雜的方式

+0

這段代碼傷害了我的心臟 – Dason 2015-03-19 12:48:54

+0

感謝Dason,我試着用最老的方法解決我的問題,因爲我是R中的新用戶 – 2015-03-19 19:45:32

回答

2
# 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" 

而且花很少的時間來運行。